xref: /linux/fs/smb/server/smb2pdu.c (revision f416c556997aa56ec4384c6b6efd6a0e6ac70aa7)
1 // SPDX-License-Identifier: GPL-2.0-or-later
2 /*
3  *   Copyright (C) 2016 Namjae Jeon <linkinjeon@kernel.org>
4  *   Copyright (C) 2018 Samsung Electronics Co., Ltd.
5  */
6 
7 #include <linux/inetdevice.h>
8 #include <net/addrconf.h>
9 #include <linux/syscalls.h>
10 #include <linux/namei.h>
11 #include <linux/statfs.h>
12 #include <linux/ethtool.h>
13 #include <linux/falloc.h>
14 #include <linux/mount.h>
15 #include <linux/filelock.h>
16 
17 #include "glob.h"
18 #include "smbfsctl.h"
19 #include "oplock.h"
20 #include "smbacl.h"
21 
22 #include "auth.h"
23 #include "asn1.h"
24 #include "connection.h"
25 #include "transport_ipc.h"
26 #include "../common/smbdirect/smbdirect.h"
27 #include "transport_rdma.h"
28 #include "vfs.h"
29 #include "vfs_cache.h"
30 #include "misc.h"
31 
32 #include "server.h"
33 #include "smb_common.h"
34 #include "../common/smb2status.h"
35 #include "ksmbd_work.h"
36 #include "mgmt/user_config.h"
37 #include "mgmt/share_config.h"
38 #include "mgmt/tree_connect.h"
39 #include "mgmt/user_session.h"
40 #include "mgmt/ksmbd_ida.h"
41 #include "ndr.h"
42 #include "transport_tcp.h"
43 
44 static void __wbuf(struct ksmbd_work *work, void **req, void **rsp)
45 {
46 	if (work->next_smb2_rcv_hdr_off) {
47 		*req = ksmbd_req_buf_next(work);
48 		*rsp = ksmbd_resp_buf_next(work);
49 	} else {
50 		*req = smb_get_msg(work->request_buf);
51 		*rsp = smb_get_msg(work->response_buf);
52 	}
53 }
54 
55 #define WORK_BUFFERS(w, rq, rs)	__wbuf((w), (void **)&(rq), (void **)&(rs))
56 
57 /**
58  * check_session_id() - check for valid session id in smb header
59  * @conn:	connection instance
60  * @id:		session id from smb header
61  *
62  * Return:      1 if valid session id, otherwise 0
63  */
64 static inline bool check_session_id(struct ksmbd_conn *conn, u64 id)
65 {
66 	struct ksmbd_session *sess;
67 
68 	if (id == 0 || id == -1)
69 		return false;
70 
71 	sess = ksmbd_session_lookup_all(conn, id);
72 	if (sess) {
73 		ksmbd_user_session_put(sess);
74 		return true;
75 	}
76 	pr_err("Invalid user session id: %llu\n", id);
77 	return false;
78 }
79 
80 struct channel *lookup_chann_list(struct ksmbd_session *sess, struct ksmbd_conn *conn)
81 {
82 	return xa_load(&sess->ksmbd_chann_list, (long)conn);
83 }
84 
85 /**
86  * smb2_get_ksmbd_tcon() - get tree connection information using a tree id.
87  * @work:	smb work
88  *
89  * Return:	0 if there is a tree connection matched or these are
90  *		skipable commands, otherwise error
91  */
92 int smb2_get_ksmbd_tcon(struct ksmbd_work *work)
93 {
94 	struct smb2_hdr *req_hdr = ksmbd_req_buf_next(work);
95 	unsigned int cmd = le16_to_cpu(req_hdr->Command);
96 	unsigned int tree_id;
97 
98 	if (cmd == SMB2_TREE_CONNECT_HE ||
99 	    cmd ==  SMB2_CANCEL_HE ||
100 	    cmd ==  SMB2_LOGOFF_HE) {
101 		ksmbd_debug(SMB, "skip to check tree connect request\n");
102 		return 0;
103 	}
104 
105 	if (xa_empty(&work->sess->tree_conns)) {
106 		ksmbd_debug(SMB, "NO tree connected\n");
107 		return -ENOENT;
108 	}
109 
110 	tree_id = le32_to_cpu(req_hdr->Id.SyncId.TreeId);
111 
112 	/*
113 	 * If request is not the first in Compound request,
114 	 * Just validate tree id in header with work->tcon->id.
115 	 */
116 	if (work->next_smb2_rcv_hdr_off) {
117 		if (!work->tcon) {
118 			pr_err("The first operation in the compound does not have tcon\n");
119 			return -EINVAL;
120 		}
121 		if (tree_id != UINT_MAX && work->tcon->id != tree_id) {
122 			pr_err("tree id(%u) is different with id(%u) in first operation\n",
123 					tree_id, work->tcon->id);
124 			return -EINVAL;
125 		}
126 		return 1;
127 	}
128 
129 	work->tcon = ksmbd_tree_conn_lookup(work->sess, tree_id);
130 	if (!work->tcon) {
131 		pr_err("Invalid tid %d\n", tree_id);
132 		return -ENOENT;
133 	}
134 
135 	return 1;
136 }
137 
138 /**
139  * smb2_set_err_rsp() - set error response code on smb response
140  * @work:	smb work containing response buffer
141  */
142 void smb2_set_err_rsp(struct ksmbd_work *work)
143 {
144 	struct smb2_err_rsp *err_rsp;
145 
146 	if (work->next_smb2_rcv_hdr_off)
147 		err_rsp = ksmbd_resp_buf_next(work);
148 	else
149 		err_rsp = smb_get_msg(work->response_buf);
150 
151 	if (err_rsp->hdr.Status != STATUS_STOPPED_ON_SYMLINK) {
152 		int err;
153 
154 		err_rsp->StructureSize = SMB2_ERROR_STRUCTURE_SIZE2_LE;
155 		err_rsp->ErrorContextCount = 0;
156 		err_rsp->Reserved = 0;
157 		err_rsp->ByteCount = 0;
158 		err_rsp->ErrorData[0] = 0;
159 		err = ksmbd_iov_pin_rsp(work, (void *)err_rsp,
160 					__SMB2_HEADER_STRUCTURE_SIZE +
161 						SMB2_ERROR_STRUCTURE_SIZE2);
162 		if (err)
163 			work->send_no_response = 1;
164 	}
165 }
166 
167 /**
168  * is_smb2_neg_cmd() - is it smb2 negotiation command
169  * @work:	smb work containing smb header
170  *
171  * Return:      true if smb2 negotiation command, otherwise false
172  */
173 bool is_smb2_neg_cmd(struct ksmbd_work *work)
174 {
175 	struct smb2_hdr *hdr = smb_get_msg(work->request_buf);
176 
177 	/* is it SMB2 header ? */
178 	if (hdr->ProtocolId != SMB2_PROTO_NUMBER)
179 		return false;
180 
181 	/* make sure it is request not response message */
182 	if (hdr->Flags & SMB2_FLAGS_SERVER_TO_REDIR)
183 		return false;
184 
185 	if (hdr->Command != SMB2_NEGOTIATE)
186 		return false;
187 
188 	return true;
189 }
190 
191 /**
192  * is_smb2_rsp() - is it smb2 response
193  * @work:	smb work containing smb response buffer
194  *
195  * Return:      true if smb2 response, otherwise false
196  */
197 bool is_smb2_rsp(struct ksmbd_work *work)
198 {
199 	struct smb2_hdr *hdr = smb_get_msg(work->response_buf);
200 
201 	/* is it SMB2 header ? */
202 	if (hdr->ProtocolId != SMB2_PROTO_NUMBER)
203 		return false;
204 
205 	/* make sure it is response not request message */
206 	if (!(hdr->Flags & SMB2_FLAGS_SERVER_TO_REDIR))
207 		return false;
208 
209 	return true;
210 }
211 
212 /**
213  * get_smb2_cmd_val() - get smb command code from smb header
214  * @work:	smb work containing smb request buffer
215  *
216  * Return:      smb2 request command value
217  */
218 u16 get_smb2_cmd_val(struct ksmbd_work *work)
219 {
220 	struct smb2_hdr *rcv_hdr;
221 
222 	if (work->next_smb2_rcv_hdr_off)
223 		rcv_hdr = ksmbd_req_buf_next(work);
224 	else
225 		rcv_hdr = smb_get_msg(work->request_buf);
226 	return le16_to_cpu(rcv_hdr->Command);
227 }
228 
229 /**
230  * set_smb2_rsp_status() - set error response code on smb2 header
231  * @work:	smb work containing response buffer
232  * @err:	error response code
233  */
234 void set_smb2_rsp_status(struct ksmbd_work *work, __le32 err)
235 {
236 	struct smb2_hdr *rsp_hdr;
237 
238 	rsp_hdr = smb_get_msg(work->response_buf);
239 	rsp_hdr->Status = err;
240 
241 	work->iov_idx = 0;
242 	work->iov_cnt = 0;
243 	work->next_smb2_rcv_hdr_off = 0;
244 	smb2_set_err_rsp(work);
245 }
246 
247 /**
248  * init_smb2_neg_rsp() - initialize smb2 response for negotiate command
249  * @work:	smb work containing smb request buffer
250  *
251  * smb2 negotiate response is sent in reply of smb1 negotiate command for
252  * dialect auto-negotiation.
253  */
254 int init_smb2_neg_rsp(struct ksmbd_work *work)
255 {
256 	struct smb2_hdr *rsp_hdr;
257 	struct smb2_negotiate_rsp *rsp;
258 	struct ksmbd_conn *conn = work->conn;
259 	int err;
260 
261 	rsp_hdr = smb_get_msg(work->response_buf);
262 	memset(rsp_hdr, 0, sizeof(struct smb2_hdr) + 2);
263 	rsp_hdr->ProtocolId = SMB2_PROTO_NUMBER;
264 	rsp_hdr->StructureSize = SMB2_HEADER_STRUCTURE_SIZE;
265 	rsp_hdr->CreditRequest = cpu_to_le16(2);
266 	rsp_hdr->Command = SMB2_NEGOTIATE;
267 	rsp_hdr->Flags = (SMB2_FLAGS_SERVER_TO_REDIR);
268 	rsp_hdr->NextCommand = 0;
269 	rsp_hdr->MessageId = 0;
270 	rsp_hdr->Id.SyncId.ProcessId = 0;
271 	rsp_hdr->Id.SyncId.TreeId = 0;
272 	rsp_hdr->SessionId = 0;
273 	memset(rsp_hdr->Signature, 0, 16);
274 
275 	rsp = smb_get_msg(work->response_buf);
276 
277 	WARN_ON(ksmbd_conn_good(conn));
278 
279 	rsp->StructureSize = cpu_to_le16(65);
280 	ksmbd_debug(SMB, "conn->dialect 0x%x\n", conn->dialect);
281 	rsp->DialectRevision = cpu_to_le16(conn->dialect);
282 	/* Not setting conn guid rsp->ServerGUID, as it
283 	 * not used by client for identifying connection
284 	 */
285 	rsp->Capabilities = cpu_to_le32(conn->vals->req_capabilities);
286 	/* Default Max Message Size till SMB2.0, 64K*/
287 	rsp->MaxTransactSize = cpu_to_le32(conn->vals->max_trans_size);
288 	rsp->MaxReadSize = cpu_to_le32(conn->vals->max_read_size);
289 	rsp->MaxWriteSize = cpu_to_le32(conn->vals->max_write_size);
290 
291 	rsp->SystemTime = cpu_to_le64(ksmbd_systime());
292 	rsp->ServerStartTime = 0;
293 
294 	rsp->SecurityBufferOffset = cpu_to_le16(128);
295 	rsp->SecurityBufferLength = cpu_to_le16(AUTH_GSS_LENGTH);
296 	ksmbd_copy_gss_neg_header((char *)(&rsp->hdr) +
297 		le16_to_cpu(rsp->SecurityBufferOffset));
298 	rsp->SecurityMode = SMB2_NEGOTIATE_SIGNING_ENABLED_LE;
299 	if (server_conf.signing == KSMBD_CONFIG_OPT_MANDATORY)
300 		rsp->SecurityMode |= SMB2_NEGOTIATE_SIGNING_REQUIRED_LE;
301 	err = ksmbd_iov_pin_rsp(work, rsp,
302 				sizeof(struct smb2_negotiate_rsp) + AUTH_GSS_LENGTH);
303 	if (err)
304 		return err;
305 	conn->use_spnego = true;
306 
307 	ksmbd_conn_set_need_negotiate(conn);
308 	return 0;
309 }
310 
311 /**
312  * smb2_set_rsp_credits() - set number of credits in response buffer
313  * @work:	smb work containing smb response buffer
314  */
315 int smb2_set_rsp_credits(struct ksmbd_work *work)
316 {
317 	struct smb2_hdr *req_hdr = ksmbd_req_buf_next(work);
318 	struct smb2_hdr *hdr = ksmbd_resp_buf_next(work);
319 	struct ksmbd_conn *conn = work->conn;
320 	unsigned short credits_requested, aux_max;
321 	unsigned short credit_charge, credits_granted = 0;
322 
323 	if (work->send_no_response)
324 		return 0;
325 
326 	hdr->CreditCharge = req_hdr->CreditCharge;
327 
328 	if (conn->total_credits > conn->vals->max_credits) {
329 		hdr->CreditRequest = 0;
330 		pr_err("Total credits overflow: %d\n", conn->total_credits);
331 		return -EINVAL;
332 	}
333 
334 	credit_charge = max_t(unsigned short,
335 			      le16_to_cpu(req_hdr->CreditCharge), 1);
336 	if (credit_charge > conn->total_credits) {
337 		ksmbd_debug(SMB, "Insufficient credits granted, given: %u, granted: %u\n",
338 			    credit_charge, conn->total_credits);
339 		return -EINVAL;
340 	}
341 
342 	conn->total_credits -= credit_charge;
343 	conn->outstanding_credits -= credit_charge;
344 	credits_requested = max_t(unsigned short,
345 				  le16_to_cpu(req_hdr->CreditRequest), 1);
346 
347 	/* according to smb2.credits smbtorture, Windows server
348 	 * 2016 or later grant up to 8192 credits at once.
349 	 *
350 	 * TODO: Need to adjuct CreditRequest value according to
351 	 * current cpu load
352 	 */
353 	if (hdr->Command == SMB2_NEGOTIATE)
354 		aux_max = 1;
355 	else
356 		aux_max = conn->vals->max_credits - conn->total_credits;
357 	credits_granted = min_t(unsigned short, credits_requested, aux_max);
358 
359 	conn->total_credits += credits_granted;
360 	work->credits_granted += credits_granted;
361 
362 	if (!req_hdr->NextCommand) {
363 		/* Update CreditRequest in last request */
364 		hdr->CreditRequest = cpu_to_le16(work->credits_granted);
365 	}
366 	ksmbd_debug(SMB,
367 		    "credits: requested[%d] granted[%d] total_granted[%d]\n",
368 		    credits_requested, credits_granted,
369 		    conn->total_credits);
370 	return 0;
371 }
372 
373 /**
374  * init_chained_smb2_rsp() - initialize smb2 chained response
375  * @work:	smb work containing smb response buffer
376  */
377 static void init_chained_smb2_rsp(struct ksmbd_work *work)
378 {
379 	struct smb2_hdr *req = ksmbd_req_buf_next(work);
380 	struct smb2_hdr *rsp = ksmbd_resp_buf_next(work);
381 	struct smb2_hdr *rsp_hdr;
382 	struct smb2_hdr *rcv_hdr;
383 	int next_hdr_offset = 0;
384 	int len, new_len;
385 
386 	/* Len of this response = updated RFC len - offset of previous cmd
387 	 * in the compound rsp
388 	 */
389 
390 	/* Storing the current local FID which may be needed by subsequent
391 	 * command in the compound request
392 	 */
393 	if (req->Command == SMB2_CREATE && rsp->Status == STATUS_SUCCESS) {
394 		work->compound_fid = ((struct smb2_create_rsp *)rsp)->VolatileFileId;
395 		work->compound_pfid = ((struct smb2_create_rsp *)rsp)->PersistentFileId;
396 		work->compound_sid = le64_to_cpu(rsp->SessionId);
397 	}
398 
399 	len = get_rfc1002_len(work->response_buf) - work->next_smb2_rsp_hdr_off;
400 	next_hdr_offset = le32_to_cpu(req->NextCommand);
401 
402 	new_len = ALIGN(len, 8);
403 	work->iov[work->iov_idx].iov_len += (new_len - len);
404 	inc_rfc1001_len(work->response_buf, new_len - len);
405 	rsp->NextCommand = cpu_to_le32(new_len);
406 
407 	work->next_smb2_rcv_hdr_off += next_hdr_offset;
408 	work->curr_smb2_rsp_hdr_off = work->next_smb2_rsp_hdr_off;
409 	work->next_smb2_rsp_hdr_off += new_len;
410 	ksmbd_debug(SMB,
411 		    "Compound req new_len = %d rcv off = %d rsp off = %d\n",
412 		    new_len, work->next_smb2_rcv_hdr_off,
413 		    work->next_smb2_rsp_hdr_off);
414 
415 	rsp_hdr = ksmbd_resp_buf_next(work);
416 	rcv_hdr = ksmbd_req_buf_next(work);
417 
418 	if (!(rcv_hdr->Flags & SMB2_FLAGS_RELATED_OPERATIONS)) {
419 		ksmbd_debug(SMB, "related flag should be set\n");
420 		work->compound_fid = KSMBD_NO_FID;
421 		work->compound_pfid = KSMBD_NO_FID;
422 	}
423 	memset((char *)rsp_hdr, 0, sizeof(struct smb2_hdr) + 2);
424 	rsp_hdr->ProtocolId = SMB2_PROTO_NUMBER;
425 	rsp_hdr->StructureSize = SMB2_HEADER_STRUCTURE_SIZE;
426 	rsp_hdr->Command = rcv_hdr->Command;
427 
428 	/*
429 	 * Message is response. We don't grant oplock yet.
430 	 */
431 	rsp_hdr->Flags = (SMB2_FLAGS_SERVER_TO_REDIR |
432 				SMB2_FLAGS_RELATED_OPERATIONS);
433 	rsp_hdr->NextCommand = 0;
434 	rsp_hdr->MessageId = rcv_hdr->MessageId;
435 	rsp_hdr->Id.SyncId.ProcessId = rcv_hdr->Id.SyncId.ProcessId;
436 	rsp_hdr->Id.SyncId.TreeId = rcv_hdr->Id.SyncId.TreeId;
437 	rsp_hdr->SessionId = rcv_hdr->SessionId;
438 	memcpy(rsp_hdr->Signature, rcv_hdr->Signature, 16);
439 }
440 
441 /**
442  * is_chained_smb2_message() - check for chained command
443  * @work:	smb work containing smb request buffer
444  *
445  * Return:      true if chained request, otherwise false
446  */
447 bool is_chained_smb2_message(struct ksmbd_work *work)
448 {
449 	struct smb2_hdr *hdr = smb_get_msg(work->request_buf);
450 	unsigned int len, next_cmd;
451 
452 	if (hdr->ProtocolId != SMB2_PROTO_NUMBER)
453 		return false;
454 
455 	hdr = ksmbd_req_buf_next(work);
456 	next_cmd = le32_to_cpu(hdr->NextCommand);
457 	if (next_cmd > 0) {
458 		if ((u64)work->next_smb2_rcv_hdr_off + next_cmd +
459 			__SMB2_HEADER_STRUCTURE_SIZE >
460 		    get_rfc1002_len(work->request_buf)) {
461 			pr_err("next command(%u) offset exceeds smb msg size\n",
462 			       next_cmd);
463 			return false;
464 		}
465 
466 		if ((u64)get_rfc1002_len(work->response_buf) + MAX_CIFS_SMALL_BUFFER_SIZE >
467 		    work->response_sz) {
468 			pr_err("next response offset exceeds response buffer size\n");
469 			return false;
470 		}
471 
472 		ksmbd_debug(SMB, "got SMB2 chained command\n");
473 		init_chained_smb2_rsp(work);
474 		return true;
475 	} else if (work->next_smb2_rcv_hdr_off) {
476 		/*
477 		 * This is last request in chained command,
478 		 * align response to 8 byte
479 		 */
480 		len = ALIGN(get_rfc1002_len(work->response_buf), 8);
481 		len = len - get_rfc1002_len(work->response_buf);
482 		if (len) {
483 			ksmbd_debug(SMB, "padding len %u\n", len);
484 			work->iov[work->iov_idx].iov_len += len;
485 			inc_rfc1001_len(work->response_buf, len);
486 		}
487 		work->curr_smb2_rsp_hdr_off = work->next_smb2_rsp_hdr_off;
488 	}
489 	return false;
490 }
491 
492 /**
493  * init_smb2_rsp_hdr() - initialize smb2 response
494  * @work:	smb work containing smb request buffer
495  *
496  * Return:      0
497  */
498 int init_smb2_rsp_hdr(struct ksmbd_work *work)
499 {
500 	struct smb2_hdr *rsp_hdr = smb_get_msg(work->response_buf);
501 	struct smb2_hdr *rcv_hdr = smb_get_msg(work->request_buf);
502 
503 	memset(rsp_hdr, 0, sizeof(struct smb2_hdr) + 2);
504 	rsp_hdr->ProtocolId = rcv_hdr->ProtocolId;
505 	rsp_hdr->StructureSize = SMB2_HEADER_STRUCTURE_SIZE;
506 	rsp_hdr->Command = rcv_hdr->Command;
507 
508 	/*
509 	 * Message is response. We don't grant oplock yet.
510 	 */
511 	rsp_hdr->Flags = (SMB2_FLAGS_SERVER_TO_REDIR);
512 	rsp_hdr->NextCommand = 0;
513 	rsp_hdr->MessageId = rcv_hdr->MessageId;
514 	rsp_hdr->Id.SyncId.ProcessId = rcv_hdr->Id.SyncId.ProcessId;
515 	rsp_hdr->Id.SyncId.TreeId = rcv_hdr->Id.SyncId.TreeId;
516 	rsp_hdr->SessionId = rcv_hdr->SessionId;
517 	memcpy(rsp_hdr->Signature, rcv_hdr->Signature, 16);
518 
519 	return 0;
520 }
521 
522 /**
523  * smb2_allocate_rsp_buf() - allocate smb2 response buffer
524  * @work:	smb work containing smb request buffer
525  *
526  * Return:      0 on success, otherwise error
527  */
528 int smb2_allocate_rsp_buf(struct ksmbd_work *work)
529 {
530 	struct smb2_hdr *hdr = smb_get_msg(work->request_buf);
531 	size_t small_sz = MAX_CIFS_SMALL_BUFFER_SIZE;
532 	size_t large_sz = small_sz + work->conn->vals->max_trans_size;
533 	size_t sz = small_sz;
534 	int cmd = le16_to_cpu(hdr->Command);
535 
536 	if (cmd == SMB2_IOCTL_HE || cmd == SMB2_QUERY_DIRECTORY_HE)
537 		sz = large_sz;
538 
539 	if (cmd == SMB2_QUERY_INFO_HE) {
540 		struct smb2_query_info_req *req;
541 
542 		if (get_rfc1002_len(work->request_buf) <
543 		    offsetof(struct smb2_query_info_req, OutputBufferLength))
544 			return -EINVAL;
545 
546 		req = smb_get_msg(work->request_buf);
547 		if ((req->InfoType == SMB2_O_INFO_FILE &&
548 		     (req->FileInfoClass == FILE_FULL_EA_INFORMATION ||
549 		     req->FileInfoClass == FILE_ALL_INFORMATION)) ||
550 		    req->InfoType == SMB2_O_INFO_SECURITY)
551 			sz = large_sz;
552 	}
553 
554 	/* allocate large response buf for chained commands */
555 	if (le32_to_cpu(hdr->NextCommand) > 0)
556 		sz = large_sz;
557 
558 	work->response_buf = kvzalloc(sz, KSMBD_DEFAULT_GFP);
559 	if (!work->response_buf)
560 		return -ENOMEM;
561 
562 	work->response_sz = sz;
563 	return 0;
564 }
565 
566 /**
567  * smb2_check_user_session() - check for valid session for a user
568  * @work:	smb work containing smb request buffer
569  *
570  * Return:      0 on success, otherwise error
571  */
572 int smb2_check_user_session(struct ksmbd_work *work)
573 {
574 	struct smb2_hdr *req_hdr = ksmbd_req_buf_next(work);
575 	struct ksmbd_conn *conn = work->conn;
576 	unsigned int cmd = le16_to_cpu(req_hdr->Command);
577 	unsigned long long sess_id;
578 
579 	/*
580 	 * SMB2_ECHO, SMB2_NEGOTIATE, SMB2_SESSION_SETUP command do not
581 	 * require a session id, so no need to validate user session's for
582 	 * these commands.
583 	 */
584 	if (cmd == SMB2_ECHO_HE || cmd == SMB2_NEGOTIATE_HE ||
585 	    cmd == SMB2_SESSION_SETUP_HE)
586 		return 0;
587 
588 	if (!ksmbd_conn_good(conn))
589 		return -EIO;
590 
591 	sess_id = le64_to_cpu(req_hdr->SessionId);
592 
593 	/*
594 	 * If request is not the first in Compound request,
595 	 * Just validate session id in header with work->sess->id.
596 	 */
597 	if (work->next_smb2_rcv_hdr_off) {
598 		if (!work->sess) {
599 			pr_err("The first operation in the compound does not have sess\n");
600 			return -EINVAL;
601 		}
602 		if (sess_id != ULLONG_MAX && work->sess->id != sess_id) {
603 			pr_err("session id(%llu) is different with the first operation(%lld)\n",
604 					sess_id, work->sess->id);
605 			return -EINVAL;
606 		}
607 		return 1;
608 	}
609 
610 	/* Check for validity of user session */
611 	work->sess = ksmbd_session_lookup_all(conn, sess_id);
612 	if (work->sess)
613 		return 1;
614 	ksmbd_debug(SMB, "Invalid user session, Uid %llu\n", sess_id);
615 	return -ENOENT;
616 }
617 
618 /**
619  * smb2_get_name() - get filename string from on the wire smb format
620  * @src:	source buffer
621  * @maxlen:	maxlen of source string
622  * @local_nls:	nls_table pointer
623  *
624  * Return:      matching converted filename on success, otherwise error ptr
625  */
626 static char *
627 smb2_get_name(const char *src, const int maxlen, struct nls_table *local_nls)
628 {
629 	char *name;
630 
631 	name = smb_strndup_from_utf16(src, maxlen, 1, local_nls);
632 	if (IS_ERR(name)) {
633 		pr_err("failed to get name %ld\n", PTR_ERR(name));
634 		return name;
635 	}
636 
637 	if (*name == '\0') {
638 		kfree(name);
639 		return ERR_PTR(-EINVAL);
640 	}
641 
642 	if (*name == '\\') {
643 		pr_err("not allow directory name included leading slash\n");
644 		kfree(name);
645 		return ERR_PTR(-EINVAL);
646 	}
647 
648 	ksmbd_conv_path_to_unix(name);
649 	ksmbd_strip_last_slash(name);
650 	return name;
651 }
652 
653 int setup_async_work(struct ksmbd_work *work, void (*fn)(void **), void **arg)
654 {
655 	struct ksmbd_conn *conn = work->conn;
656 	int id;
657 
658 	id = ksmbd_acquire_async_msg_id(&conn->async_ida);
659 	if (id < 0) {
660 		pr_err("Failed to alloc async message id\n");
661 		return id;
662 	}
663 	work->asynchronous = true;
664 	work->async_id = id;
665 
666 	ksmbd_debug(SMB,
667 		    "Send interim Response to inform async request id : %d\n",
668 		    work->async_id);
669 
670 	work->cancel_fn = fn;
671 	work->cancel_argv = arg;
672 
673 	if (list_empty(&work->async_request_entry)) {
674 		spin_lock(&conn->request_lock);
675 		list_add_tail(&work->async_request_entry, &conn->async_requests);
676 		spin_unlock(&conn->request_lock);
677 	}
678 
679 	return 0;
680 }
681 
682 void release_async_work(struct ksmbd_work *work)
683 {
684 	struct ksmbd_conn *conn = work->conn;
685 
686 	spin_lock(&conn->request_lock);
687 	list_del_init(&work->async_request_entry);
688 	spin_unlock(&conn->request_lock);
689 
690 	work->asynchronous = 0;
691 	work->cancel_fn = NULL;
692 	kfree(work->cancel_argv);
693 	work->cancel_argv = NULL;
694 	if (work->async_id) {
695 		ksmbd_release_id(&conn->async_ida, work->async_id);
696 		work->async_id = 0;
697 	}
698 }
699 
700 void smb2_send_interim_resp(struct ksmbd_work *work, __le32 status)
701 {
702 	struct smb2_hdr *rsp_hdr;
703 	struct ksmbd_work *in_work = ksmbd_alloc_work_struct();
704 
705 	if (!in_work)
706 		return;
707 
708 	if (allocate_interim_rsp_buf(in_work)) {
709 		pr_err("smb_allocate_rsp_buf failed!\n");
710 		ksmbd_free_work_struct(in_work);
711 		return;
712 	}
713 
714 	in_work->conn = work->conn;
715 	memcpy(smb_get_msg(in_work->response_buf), ksmbd_resp_buf_next(work),
716 	       __SMB2_HEADER_STRUCTURE_SIZE);
717 
718 	rsp_hdr = smb_get_msg(in_work->response_buf);
719 	rsp_hdr->Flags |= SMB2_FLAGS_ASYNC_COMMAND;
720 	rsp_hdr->Id.AsyncId = cpu_to_le64(work->async_id);
721 	smb2_set_err_rsp(in_work);
722 	rsp_hdr->Status = status;
723 
724 	ksmbd_conn_write(in_work);
725 	ksmbd_free_work_struct(in_work);
726 }
727 
728 static __le32 smb2_get_reparse_tag_special_file(umode_t mode)
729 {
730 	if (S_ISDIR(mode) || S_ISREG(mode))
731 		return 0;
732 
733 	if (S_ISLNK(mode))
734 		return IO_REPARSE_TAG_LX_SYMLINK_LE;
735 	else if (S_ISFIFO(mode))
736 		return IO_REPARSE_TAG_LX_FIFO_LE;
737 	else if (S_ISSOCK(mode))
738 		return IO_REPARSE_TAG_AF_UNIX_LE;
739 	else if (S_ISCHR(mode))
740 		return IO_REPARSE_TAG_LX_CHR_LE;
741 	else if (S_ISBLK(mode))
742 		return IO_REPARSE_TAG_LX_BLK_LE;
743 
744 	return 0;
745 }
746 
747 /**
748  * smb2_get_dos_mode() - get file mode in dos format from unix mode
749  * @stat:	kstat containing file mode
750  * @attribute:	attribute flags
751  *
752  * Return:      converted dos mode
753  */
754 static int smb2_get_dos_mode(struct kstat *stat, int attribute)
755 {
756 	int attr = 0;
757 
758 	if (S_ISDIR(stat->mode)) {
759 		attr = FILE_ATTRIBUTE_DIRECTORY |
760 			(attribute & (FILE_ATTRIBUTE_HIDDEN | FILE_ATTRIBUTE_SYSTEM));
761 	} else {
762 		attr = (attribute & 0x00005137) | FILE_ATTRIBUTE_ARCHIVE;
763 		attr &= ~(FILE_ATTRIBUTE_DIRECTORY);
764 		if (S_ISREG(stat->mode) && (server_conf.share_fake_fscaps &
765 				FILE_SUPPORTS_SPARSE_FILES))
766 			attr |= FILE_ATTRIBUTE_SPARSE_FILE;
767 
768 		if (smb2_get_reparse_tag_special_file(stat->mode))
769 			attr |= FILE_ATTRIBUTE_REPARSE_POINT;
770 	}
771 
772 	return attr;
773 }
774 
775 static void build_preauth_ctxt(struct smb2_preauth_neg_context *pneg_ctxt,
776 			       __le16 hash_id)
777 {
778 	pneg_ctxt->ContextType = SMB2_PREAUTH_INTEGRITY_CAPABILITIES;
779 	pneg_ctxt->DataLength = cpu_to_le16(38);
780 	pneg_ctxt->HashAlgorithmCount = cpu_to_le16(1);
781 	pneg_ctxt->Reserved = cpu_to_le32(0);
782 	pneg_ctxt->SaltLength = cpu_to_le16(SMB311_SALT_SIZE);
783 	get_random_bytes(pneg_ctxt->Salt, SMB311_SALT_SIZE);
784 	pneg_ctxt->HashAlgorithms = hash_id;
785 }
786 
787 static void build_encrypt_ctxt(struct smb2_encryption_neg_context *pneg_ctxt,
788 			       __le16 cipher_type)
789 {
790 	pneg_ctxt->ContextType = SMB2_ENCRYPTION_CAPABILITIES;
791 	pneg_ctxt->DataLength = cpu_to_le16(4);
792 	pneg_ctxt->Reserved = cpu_to_le32(0);
793 	pneg_ctxt->CipherCount = cpu_to_le16(1);
794 	pneg_ctxt->Ciphers[0] = cipher_type;
795 }
796 
797 static void build_sign_cap_ctxt(struct smb2_signing_capabilities *pneg_ctxt,
798 				__le16 sign_algo)
799 {
800 	pneg_ctxt->ContextType = SMB2_SIGNING_CAPABILITIES;
801 	pneg_ctxt->DataLength =
802 		cpu_to_le16((sizeof(struct smb2_signing_capabilities) + 2)
803 			- sizeof(struct smb2_neg_context));
804 	pneg_ctxt->Reserved = cpu_to_le32(0);
805 	pneg_ctxt->SigningAlgorithmCount = cpu_to_le16(1);
806 	pneg_ctxt->SigningAlgorithms[0] = sign_algo;
807 }
808 
809 static void build_posix_ctxt(struct smb2_posix_neg_context *pneg_ctxt)
810 {
811 	pneg_ctxt->ContextType = SMB2_POSIX_EXTENSIONS_AVAILABLE;
812 	pneg_ctxt->DataLength = cpu_to_le16(POSIX_CTXT_DATA_LEN);
813 	/* SMB2_CREATE_TAG_POSIX is "0x93AD25509CB411E7B42383DE968BCD7C" */
814 	pneg_ctxt->Name[0] = 0x93;
815 	pneg_ctxt->Name[1] = 0xAD;
816 	pneg_ctxt->Name[2] = 0x25;
817 	pneg_ctxt->Name[3] = 0x50;
818 	pneg_ctxt->Name[4] = 0x9C;
819 	pneg_ctxt->Name[5] = 0xB4;
820 	pneg_ctxt->Name[6] = 0x11;
821 	pneg_ctxt->Name[7] = 0xE7;
822 	pneg_ctxt->Name[8] = 0xB4;
823 	pneg_ctxt->Name[9] = 0x23;
824 	pneg_ctxt->Name[10] = 0x83;
825 	pneg_ctxt->Name[11] = 0xDE;
826 	pneg_ctxt->Name[12] = 0x96;
827 	pneg_ctxt->Name[13] = 0x8B;
828 	pneg_ctxt->Name[14] = 0xCD;
829 	pneg_ctxt->Name[15] = 0x7C;
830 }
831 
832 static unsigned int assemble_neg_contexts(struct ksmbd_conn *conn,
833 				  struct smb2_negotiate_rsp *rsp)
834 {
835 	char * const pneg_ctxt = (char *)rsp +
836 			le32_to_cpu(rsp->NegotiateContextOffset);
837 	int neg_ctxt_cnt = 1;
838 	int ctxt_size;
839 
840 	ksmbd_debug(SMB,
841 		    "assemble SMB2_PREAUTH_INTEGRITY_CAPABILITIES context\n");
842 	build_preauth_ctxt((struct smb2_preauth_neg_context *)pneg_ctxt,
843 			   conn->preauth_info->Preauth_HashId);
844 	ctxt_size = sizeof(struct smb2_preauth_neg_context);
845 
846 	if (conn->cipher_type) {
847 		/* Round to 8 byte boundary */
848 		ctxt_size = round_up(ctxt_size, 8);
849 		ksmbd_debug(SMB,
850 			    "assemble SMB2_ENCRYPTION_CAPABILITIES context\n");
851 		build_encrypt_ctxt((struct smb2_encryption_neg_context *)
852 				   (pneg_ctxt + ctxt_size),
853 				   conn->cipher_type);
854 		neg_ctxt_cnt++;
855 		ctxt_size += sizeof(struct smb2_encryption_neg_context) + 2;
856 	}
857 
858 	/* compression context not yet supported */
859 	WARN_ON(conn->compress_algorithm != SMB3_COMPRESS_NONE);
860 
861 	if (conn->posix_ext_supported) {
862 		ctxt_size = round_up(ctxt_size, 8);
863 		ksmbd_debug(SMB,
864 			    "assemble SMB2_POSIX_EXTENSIONS_AVAILABLE context\n");
865 		build_posix_ctxt((struct smb2_posix_neg_context *)
866 				 (pneg_ctxt + ctxt_size));
867 		neg_ctxt_cnt++;
868 		ctxt_size += sizeof(struct smb2_posix_neg_context);
869 	}
870 
871 	if (conn->signing_negotiated) {
872 		ctxt_size = round_up(ctxt_size, 8);
873 		ksmbd_debug(SMB,
874 			    "assemble SMB2_SIGNING_CAPABILITIES context\n");
875 		build_sign_cap_ctxt((struct smb2_signing_capabilities *)
876 				    (pneg_ctxt + ctxt_size),
877 				    conn->signing_algorithm);
878 		neg_ctxt_cnt++;
879 		ctxt_size += sizeof(struct smb2_signing_capabilities) + 2;
880 	}
881 
882 	rsp->NegotiateContextCount = cpu_to_le16(neg_ctxt_cnt);
883 	return ctxt_size + AUTH_GSS_PADDING;
884 }
885 
886 static __le32 decode_preauth_ctxt(struct ksmbd_conn *conn,
887 				  struct smb2_preauth_neg_context *pneg_ctxt,
888 				  int ctxt_len)
889 {
890 	/*
891 	 * sizeof(smb2_preauth_neg_context) assumes SMB311_SALT_SIZE Salt,
892 	 * which may not be present. Only check for used HashAlgorithms[1].
893 	 */
894 	if (ctxt_len <
895 	    sizeof(struct smb2_neg_context) + MIN_PREAUTH_CTXT_DATA_LEN)
896 		return STATUS_INVALID_PARAMETER;
897 
898 	if (pneg_ctxt->HashAlgorithms != SMB2_PREAUTH_INTEGRITY_SHA512)
899 		return STATUS_SMB_NO_PREAUTH_INTEGRITY_HASH_OVERLAP;
900 
901 	conn->preauth_info->Preauth_HashId = SMB2_PREAUTH_INTEGRITY_SHA512;
902 	return STATUS_SUCCESS;
903 }
904 
905 static void decode_encrypt_ctxt(struct ksmbd_conn *conn,
906 				struct smb2_encryption_neg_context *pneg_ctxt,
907 				int ctxt_len)
908 {
909 	int cph_cnt;
910 	int i, cphs_size;
911 
912 	if (sizeof(struct smb2_encryption_neg_context) > ctxt_len) {
913 		pr_err("Invalid SMB2_ENCRYPTION_CAPABILITIES context size\n");
914 		return;
915 	}
916 
917 	conn->cipher_type = 0;
918 
919 	cph_cnt = le16_to_cpu(pneg_ctxt->CipherCount);
920 	cphs_size = cph_cnt * sizeof(__le16);
921 
922 	if (sizeof(struct smb2_encryption_neg_context) + cphs_size >
923 	    ctxt_len) {
924 		pr_err("Invalid cipher count(%d)\n", cph_cnt);
925 		return;
926 	}
927 
928 	if (server_conf.flags & KSMBD_GLOBAL_FLAG_SMB2_ENCRYPTION_OFF)
929 		return;
930 
931 	for (i = 0; i < cph_cnt; i++) {
932 		if (pneg_ctxt->Ciphers[i] == SMB2_ENCRYPTION_AES128_GCM ||
933 		    pneg_ctxt->Ciphers[i] == SMB2_ENCRYPTION_AES128_CCM ||
934 		    pneg_ctxt->Ciphers[i] == SMB2_ENCRYPTION_AES256_CCM ||
935 		    pneg_ctxt->Ciphers[i] == SMB2_ENCRYPTION_AES256_GCM) {
936 			ksmbd_debug(SMB, "Cipher ID = 0x%x\n",
937 				    pneg_ctxt->Ciphers[i]);
938 			conn->cipher_type = pneg_ctxt->Ciphers[i];
939 			break;
940 		}
941 	}
942 }
943 
944 /**
945  * smb3_encryption_negotiated() - checks if server and client agreed on enabling encryption
946  * @conn:	smb connection
947  *
948  * Return:	true if connection should be encrypted, else false
949  */
950 bool smb3_encryption_negotiated(struct ksmbd_conn *conn)
951 {
952 	if (!conn->ops->generate_encryptionkey)
953 		return false;
954 
955 	/*
956 	 * SMB 3.0 and 3.0.2 dialects use the SMB2_GLOBAL_CAP_ENCRYPTION flag.
957 	 * SMB 3.1.1 uses the cipher_type field.
958 	 */
959 	return (conn->vals->req_capabilities & SMB2_GLOBAL_CAP_ENCRYPTION) ||
960 	    conn->cipher_type;
961 }
962 
963 static void decode_compress_ctxt(struct ksmbd_conn *conn,
964 				 struct smb2_compression_capabilities_context *pneg_ctxt)
965 {
966 	conn->compress_algorithm = SMB3_COMPRESS_NONE;
967 }
968 
969 static void decode_sign_cap_ctxt(struct ksmbd_conn *conn,
970 				 struct smb2_signing_capabilities *pneg_ctxt,
971 				 int ctxt_len)
972 {
973 	int sign_algo_cnt;
974 	int i, sign_alos_size;
975 
976 	if (sizeof(struct smb2_signing_capabilities) > ctxt_len) {
977 		pr_err("Invalid SMB2_SIGNING_CAPABILITIES context length\n");
978 		return;
979 	}
980 
981 	conn->signing_negotiated = false;
982 	sign_algo_cnt = le16_to_cpu(pneg_ctxt->SigningAlgorithmCount);
983 	sign_alos_size = sign_algo_cnt * sizeof(__le16);
984 
985 	if (sizeof(struct smb2_signing_capabilities) + sign_alos_size >
986 	    ctxt_len) {
987 		pr_err("Invalid signing algorithm count(%d)\n", sign_algo_cnt);
988 		return;
989 	}
990 
991 	for (i = 0; i < sign_algo_cnt; i++) {
992 		if (pneg_ctxt->SigningAlgorithms[i] == SIGNING_ALG_HMAC_SHA256_LE ||
993 		    pneg_ctxt->SigningAlgorithms[i] == SIGNING_ALG_AES_CMAC_LE) {
994 			ksmbd_debug(SMB, "Signing Algorithm ID = 0x%x\n",
995 				    pneg_ctxt->SigningAlgorithms[i]);
996 			conn->signing_negotiated = true;
997 			conn->signing_algorithm =
998 				pneg_ctxt->SigningAlgorithms[i];
999 			break;
1000 		}
1001 	}
1002 }
1003 
1004 static __le32 deassemble_neg_contexts(struct ksmbd_conn *conn,
1005 				      struct smb2_negotiate_req *req,
1006 				      unsigned int len_of_smb)
1007 {
1008 	/* +4 is to account for the RFC1001 len field */
1009 	struct smb2_neg_context *pctx = (struct smb2_neg_context *)req;
1010 	int i = 0, len_of_ctxts;
1011 	unsigned int offset = le32_to_cpu(req->NegotiateContextOffset);
1012 	unsigned int neg_ctxt_cnt = le16_to_cpu(req->NegotiateContextCount);
1013 	__le32 status = STATUS_INVALID_PARAMETER;
1014 
1015 	ksmbd_debug(SMB, "decoding %d negotiate contexts\n", neg_ctxt_cnt);
1016 	if (len_of_smb <= offset) {
1017 		ksmbd_debug(SMB, "Invalid response: negotiate context offset\n");
1018 		return status;
1019 	}
1020 
1021 	len_of_ctxts = len_of_smb - offset;
1022 
1023 	while (i++ < neg_ctxt_cnt) {
1024 		int clen, ctxt_len;
1025 
1026 		if (len_of_ctxts < (int)sizeof(struct smb2_neg_context))
1027 			break;
1028 
1029 		pctx = (struct smb2_neg_context *)((char *)pctx + offset);
1030 		clen = le16_to_cpu(pctx->DataLength);
1031 		ctxt_len = clen + sizeof(struct smb2_neg_context);
1032 
1033 		if (ctxt_len > len_of_ctxts)
1034 			break;
1035 
1036 		if (pctx->ContextType == SMB2_PREAUTH_INTEGRITY_CAPABILITIES) {
1037 			ksmbd_debug(SMB,
1038 				    "deassemble SMB2_PREAUTH_INTEGRITY_CAPABILITIES context\n");
1039 			if (conn->preauth_info->Preauth_HashId)
1040 				break;
1041 
1042 			status = decode_preauth_ctxt(conn,
1043 						     (struct smb2_preauth_neg_context *)pctx,
1044 						     ctxt_len);
1045 			if (status != STATUS_SUCCESS)
1046 				break;
1047 		} else if (pctx->ContextType == SMB2_ENCRYPTION_CAPABILITIES) {
1048 			ksmbd_debug(SMB,
1049 				    "deassemble SMB2_ENCRYPTION_CAPABILITIES context\n");
1050 			if (conn->cipher_type)
1051 				break;
1052 
1053 			decode_encrypt_ctxt(conn,
1054 					    (struct smb2_encryption_neg_context *)pctx,
1055 					    ctxt_len);
1056 		} else if (pctx->ContextType == SMB2_COMPRESSION_CAPABILITIES) {
1057 			ksmbd_debug(SMB,
1058 				    "deassemble SMB2_COMPRESSION_CAPABILITIES context\n");
1059 			if (conn->compress_algorithm)
1060 				break;
1061 
1062 			decode_compress_ctxt(conn,
1063 					     (struct smb2_compression_capabilities_context *)pctx);
1064 		} else if (pctx->ContextType == SMB2_NETNAME_NEGOTIATE_CONTEXT_ID) {
1065 			ksmbd_debug(SMB,
1066 				    "deassemble SMB2_NETNAME_NEGOTIATE_CONTEXT_ID context\n");
1067 		} else if (pctx->ContextType == SMB2_POSIX_EXTENSIONS_AVAILABLE) {
1068 			ksmbd_debug(SMB,
1069 				    "deassemble SMB2_POSIX_EXTENSIONS_AVAILABLE context\n");
1070 			conn->posix_ext_supported = true;
1071 		} else if (pctx->ContextType == SMB2_SIGNING_CAPABILITIES) {
1072 			ksmbd_debug(SMB,
1073 				    "deassemble SMB2_SIGNING_CAPABILITIES context\n");
1074 
1075 			decode_sign_cap_ctxt(conn,
1076 					     (struct smb2_signing_capabilities *)pctx,
1077 					     ctxt_len);
1078 		}
1079 
1080 		/* offsets must be 8 byte aligned */
1081 		offset = (ctxt_len + 7) & ~0x7;
1082 		len_of_ctxts -= offset;
1083 	}
1084 	return status;
1085 }
1086 
1087 /**
1088  * smb2_handle_negotiate() - handler for smb2 negotiate command
1089  * @work:	smb work containing smb request buffer
1090  *
1091  * Return:      0
1092  */
1093 int smb2_handle_negotiate(struct ksmbd_work *work)
1094 {
1095 	struct ksmbd_conn *conn = work->conn;
1096 	struct smb2_negotiate_req *req = smb_get_msg(work->request_buf);
1097 	struct smb2_negotiate_rsp *rsp = smb_get_msg(work->response_buf);
1098 	int rc = 0;
1099 	unsigned int smb2_buf_len, smb2_neg_size, neg_ctxt_len = 0;
1100 	__le32 status;
1101 
1102 	ksmbd_debug(SMB, "Received negotiate request\n");
1103 	conn->need_neg = false;
1104 	if (ksmbd_conn_good(conn)) {
1105 		pr_err("conn->tcp_status is already in CifsGood State\n");
1106 		work->send_no_response = 1;
1107 		return rc;
1108 	}
1109 
1110 	ksmbd_conn_lock(conn);
1111 	smb2_buf_len = get_rfc1002_len(work->request_buf);
1112 	smb2_neg_size = offsetof(struct smb2_negotiate_req, Dialects);
1113 	if (smb2_neg_size > smb2_buf_len) {
1114 		rsp->hdr.Status = STATUS_INVALID_PARAMETER;
1115 		rc = -EINVAL;
1116 		goto err_out;
1117 	}
1118 
1119 	if (req->DialectCount == 0) {
1120 		pr_err("malformed packet\n");
1121 		rsp->hdr.Status = STATUS_INVALID_PARAMETER;
1122 		rc = -EINVAL;
1123 		goto err_out;
1124 	}
1125 
1126 	if (conn->dialect == SMB311_PROT_ID) {
1127 		unsigned int nego_ctxt_off = le32_to_cpu(req->NegotiateContextOffset);
1128 
1129 		if (smb2_buf_len < nego_ctxt_off) {
1130 			rsp->hdr.Status = STATUS_INVALID_PARAMETER;
1131 			rc = -EINVAL;
1132 			goto err_out;
1133 		}
1134 
1135 		if (smb2_neg_size > nego_ctxt_off) {
1136 			rsp->hdr.Status = STATUS_INVALID_PARAMETER;
1137 			rc = -EINVAL;
1138 			goto err_out;
1139 		}
1140 
1141 		if (smb2_neg_size + le16_to_cpu(req->DialectCount) * sizeof(__le16) >
1142 		    nego_ctxt_off) {
1143 			rsp->hdr.Status = STATUS_INVALID_PARAMETER;
1144 			rc = -EINVAL;
1145 			goto err_out;
1146 		}
1147 	} else {
1148 		if (smb2_neg_size + le16_to_cpu(req->DialectCount) * sizeof(__le16) >
1149 		    smb2_buf_len) {
1150 			rsp->hdr.Status = STATUS_INVALID_PARAMETER;
1151 			rc = -EINVAL;
1152 			goto err_out;
1153 		}
1154 	}
1155 
1156 	conn->cli_cap = le32_to_cpu(req->Capabilities);
1157 	switch (conn->dialect) {
1158 	case SMB311_PROT_ID:
1159 		conn->preauth_info =
1160 			kzalloc(sizeof(struct preauth_integrity_info),
1161 				KSMBD_DEFAULT_GFP);
1162 		if (!conn->preauth_info) {
1163 			rc = -ENOMEM;
1164 			rsp->hdr.Status = STATUS_INVALID_PARAMETER;
1165 			goto err_out;
1166 		}
1167 
1168 		status = deassemble_neg_contexts(conn, req,
1169 						 get_rfc1002_len(work->request_buf));
1170 		if (status != STATUS_SUCCESS) {
1171 			pr_err("deassemble_neg_contexts error(0x%x)\n",
1172 			       status);
1173 			rsp->hdr.Status = status;
1174 			rc = -EINVAL;
1175 			kfree(conn->preauth_info);
1176 			conn->preauth_info = NULL;
1177 			goto err_out;
1178 		}
1179 
1180 		rc = init_smb3_11_server(conn);
1181 		if (rc < 0) {
1182 			rsp->hdr.Status = STATUS_INVALID_PARAMETER;
1183 			kfree(conn->preauth_info);
1184 			conn->preauth_info = NULL;
1185 			goto err_out;
1186 		}
1187 
1188 		ksmbd_gen_preauth_integrity_hash(conn,
1189 						 work->request_buf,
1190 						 conn->preauth_info->Preauth_HashValue);
1191 		rsp->NegotiateContextOffset =
1192 				cpu_to_le32(OFFSET_OF_NEG_CONTEXT);
1193 		neg_ctxt_len = assemble_neg_contexts(conn, rsp);
1194 		break;
1195 	case SMB302_PROT_ID:
1196 		init_smb3_02_server(conn);
1197 		break;
1198 	case SMB30_PROT_ID:
1199 		init_smb3_0_server(conn);
1200 		break;
1201 	case SMB21_PROT_ID:
1202 		init_smb2_1_server(conn);
1203 		break;
1204 	case SMB2X_PROT_ID:
1205 	case BAD_PROT_ID:
1206 	default:
1207 		ksmbd_debug(SMB, "Server dialect :0x%x not supported\n",
1208 			    conn->dialect);
1209 		rsp->hdr.Status = STATUS_NOT_SUPPORTED;
1210 		rc = -EINVAL;
1211 		goto err_out;
1212 	}
1213 	rsp->Capabilities = cpu_to_le32(conn->vals->req_capabilities);
1214 
1215 	/* For stats */
1216 	conn->connection_type = conn->dialect;
1217 
1218 	rsp->MaxTransactSize = cpu_to_le32(conn->vals->max_trans_size);
1219 	rsp->MaxReadSize = cpu_to_le32(conn->vals->max_read_size);
1220 	rsp->MaxWriteSize = cpu_to_le32(conn->vals->max_write_size);
1221 
1222 	memcpy(conn->ClientGUID, req->ClientGUID,
1223 			SMB2_CLIENT_GUID_SIZE);
1224 	conn->cli_sec_mode = le16_to_cpu(req->SecurityMode);
1225 
1226 	rsp->StructureSize = cpu_to_le16(65);
1227 	rsp->DialectRevision = cpu_to_le16(conn->dialect);
1228 	/* Not setting conn guid rsp->ServerGUID, as it
1229 	 * not used by client for identifying server
1230 	 */
1231 	memset(rsp->ServerGUID, 0, SMB2_CLIENT_GUID_SIZE);
1232 
1233 	rsp->SystemTime = cpu_to_le64(ksmbd_systime());
1234 	rsp->ServerStartTime = 0;
1235 	ksmbd_debug(SMB, "negotiate context offset %d, count %d\n",
1236 		    le32_to_cpu(rsp->NegotiateContextOffset),
1237 		    le16_to_cpu(rsp->NegotiateContextCount));
1238 
1239 	rsp->SecurityBufferOffset = cpu_to_le16(128);
1240 	rsp->SecurityBufferLength = cpu_to_le16(AUTH_GSS_LENGTH);
1241 	ksmbd_copy_gss_neg_header((char *)(&rsp->hdr) +
1242 				  le16_to_cpu(rsp->SecurityBufferOffset));
1243 
1244 	rsp->SecurityMode = SMB2_NEGOTIATE_SIGNING_ENABLED_LE;
1245 	conn->use_spnego = true;
1246 
1247 	if ((server_conf.signing == KSMBD_CONFIG_OPT_AUTO ||
1248 	     server_conf.signing == KSMBD_CONFIG_OPT_DISABLED) &&
1249 	    req->SecurityMode & SMB2_NEGOTIATE_SIGNING_REQUIRED_LE)
1250 		conn->sign = true;
1251 	else if (server_conf.signing == KSMBD_CONFIG_OPT_MANDATORY) {
1252 		server_conf.enforced_signing = true;
1253 		rsp->SecurityMode |= SMB2_NEGOTIATE_SIGNING_REQUIRED_LE;
1254 		conn->sign = true;
1255 	}
1256 
1257 	conn->srv_sec_mode = le16_to_cpu(rsp->SecurityMode);
1258 	ksmbd_conn_set_need_setup(conn);
1259 
1260 err_out:
1261 	ksmbd_conn_unlock(conn);
1262 	if (rc)
1263 		rsp->hdr.Status = STATUS_INSUFFICIENT_RESOURCES;
1264 
1265 	if (!rc)
1266 		rc = ksmbd_iov_pin_rsp(work, rsp,
1267 				       sizeof(struct smb2_negotiate_rsp) +
1268 					AUTH_GSS_LENGTH + neg_ctxt_len);
1269 	if (rc < 0)
1270 		smb2_set_err_rsp(work);
1271 	return rc;
1272 }
1273 
1274 static int alloc_preauth_hash(struct ksmbd_session *sess,
1275 			      struct ksmbd_conn *conn)
1276 {
1277 	if (sess->Preauth_HashValue)
1278 		return 0;
1279 
1280 	if (!conn->preauth_info)
1281 		return -ENOMEM;
1282 
1283 	sess->Preauth_HashValue = kmemdup(conn->preauth_info->Preauth_HashValue,
1284 					  PREAUTH_HASHVALUE_SIZE, KSMBD_DEFAULT_GFP);
1285 	if (!sess->Preauth_HashValue)
1286 		return -ENOMEM;
1287 
1288 	return 0;
1289 }
1290 
1291 static int generate_preauth_hash(struct ksmbd_work *work)
1292 {
1293 	struct ksmbd_conn *conn = work->conn;
1294 	struct ksmbd_session *sess = work->sess;
1295 	u8 *preauth_hash;
1296 
1297 	if (conn->dialect != SMB311_PROT_ID)
1298 		return 0;
1299 
1300 	if (conn->binding) {
1301 		struct preauth_session *preauth_sess;
1302 
1303 		preauth_sess = ksmbd_preauth_session_lookup(conn, sess->id);
1304 		if (!preauth_sess) {
1305 			preauth_sess = ksmbd_preauth_session_alloc(conn, sess->id);
1306 			if (!preauth_sess)
1307 				return -ENOMEM;
1308 		}
1309 
1310 		preauth_hash = preauth_sess->Preauth_HashValue;
1311 	} else {
1312 		if (!sess->Preauth_HashValue)
1313 			if (alloc_preauth_hash(sess, conn))
1314 				return -ENOMEM;
1315 		preauth_hash = sess->Preauth_HashValue;
1316 	}
1317 
1318 	ksmbd_gen_preauth_integrity_hash(conn, work->request_buf, preauth_hash);
1319 	return 0;
1320 }
1321 
1322 static int decode_negotiation_token(struct ksmbd_conn *conn,
1323 				    struct negotiate_message *negblob,
1324 				    size_t sz)
1325 {
1326 	if (!conn->use_spnego)
1327 		return -EINVAL;
1328 
1329 	if (ksmbd_decode_negTokenInit((char *)negblob, sz, conn)) {
1330 		if (ksmbd_decode_negTokenTarg((char *)negblob, sz, conn)) {
1331 			conn->auth_mechs |= KSMBD_AUTH_NTLMSSP;
1332 			conn->preferred_auth_mech = KSMBD_AUTH_NTLMSSP;
1333 			conn->use_spnego = false;
1334 		}
1335 	}
1336 	return 0;
1337 }
1338 
1339 static int ntlm_negotiate(struct ksmbd_work *work,
1340 			  struct negotiate_message *negblob,
1341 			  size_t negblob_len, struct smb2_sess_setup_rsp *rsp)
1342 {
1343 	struct challenge_message *chgblob;
1344 	unsigned char *spnego_blob = NULL;
1345 	u16 spnego_blob_len;
1346 	char *neg_blob;
1347 	int sz, rc;
1348 
1349 	ksmbd_debug(SMB, "negotiate phase\n");
1350 	rc = ksmbd_decode_ntlmssp_neg_blob(negblob, negblob_len, work->conn);
1351 	if (rc)
1352 		return rc;
1353 
1354 	sz = le16_to_cpu(rsp->SecurityBufferOffset);
1355 	chgblob = (struct challenge_message *)rsp->Buffer;
1356 	memset(chgblob, 0, sizeof(struct challenge_message));
1357 
1358 	if (!work->conn->use_spnego) {
1359 		sz = ksmbd_build_ntlmssp_challenge_blob(chgblob, work->conn);
1360 		if (sz < 0)
1361 			return -ENOMEM;
1362 
1363 		rsp->SecurityBufferLength = cpu_to_le16(sz);
1364 		return 0;
1365 	}
1366 
1367 	sz = sizeof(struct challenge_message);
1368 	sz += (strlen(ksmbd_netbios_name()) * 2 + 1 + 4) * 6;
1369 
1370 	neg_blob = kzalloc(sz, KSMBD_DEFAULT_GFP);
1371 	if (!neg_blob)
1372 		return -ENOMEM;
1373 
1374 	chgblob = (struct challenge_message *)neg_blob;
1375 	sz = ksmbd_build_ntlmssp_challenge_blob(chgblob, work->conn);
1376 	if (sz < 0) {
1377 		rc = -ENOMEM;
1378 		goto out;
1379 	}
1380 
1381 	rc = build_spnego_ntlmssp_neg_blob(&spnego_blob, &spnego_blob_len,
1382 					   neg_blob, sz);
1383 	if (rc) {
1384 		rc = -ENOMEM;
1385 		goto out;
1386 	}
1387 
1388 	memcpy(rsp->Buffer, spnego_blob, spnego_blob_len);
1389 	rsp->SecurityBufferLength = cpu_to_le16(spnego_blob_len);
1390 
1391 out:
1392 	kfree(spnego_blob);
1393 	kfree(neg_blob);
1394 	return rc;
1395 }
1396 
1397 static struct authenticate_message *user_authblob(struct ksmbd_conn *conn,
1398 						  struct smb2_sess_setup_req *req)
1399 {
1400 	int sz;
1401 
1402 	if (conn->use_spnego && conn->mechToken)
1403 		return (struct authenticate_message *)conn->mechToken;
1404 
1405 	sz = le16_to_cpu(req->SecurityBufferOffset);
1406 	return (struct authenticate_message *)((char *)&req->hdr.ProtocolId
1407 					       + sz);
1408 }
1409 
1410 static struct ksmbd_user *session_user(struct ksmbd_conn *conn,
1411 				       struct smb2_sess_setup_req *req)
1412 {
1413 	struct authenticate_message *authblob;
1414 	struct ksmbd_user *user;
1415 	char *name;
1416 	unsigned int name_off, name_len, secbuf_len;
1417 
1418 	if (conn->use_spnego && conn->mechToken)
1419 		secbuf_len = conn->mechTokenLen;
1420 	else
1421 		secbuf_len = le16_to_cpu(req->SecurityBufferLength);
1422 	if (secbuf_len < sizeof(struct authenticate_message)) {
1423 		ksmbd_debug(SMB, "blob len %d too small\n", secbuf_len);
1424 		return NULL;
1425 	}
1426 	authblob = user_authblob(conn, req);
1427 	name_off = le32_to_cpu(authblob->UserName.BufferOffset);
1428 	name_len = le16_to_cpu(authblob->UserName.Length);
1429 
1430 	if (secbuf_len < (u64)name_off + name_len)
1431 		return NULL;
1432 
1433 	name = smb_strndup_from_utf16((const char *)authblob + name_off,
1434 				      name_len,
1435 				      true,
1436 				      conn->local_nls);
1437 	if (IS_ERR(name)) {
1438 		pr_err("cannot allocate memory\n");
1439 		return NULL;
1440 	}
1441 
1442 	ksmbd_debug(SMB, "session setup request for user %s\n", name);
1443 	user = ksmbd_login_user(name);
1444 	kfree(name);
1445 	return user;
1446 }
1447 
1448 static int ntlm_authenticate(struct ksmbd_work *work,
1449 			     struct smb2_sess_setup_req *req,
1450 			     struct smb2_sess_setup_rsp *rsp)
1451 {
1452 	struct ksmbd_conn *conn = work->conn;
1453 	struct ksmbd_session *sess = work->sess;
1454 	struct channel *chann = NULL, *old;
1455 	struct ksmbd_user *user;
1456 	u64 prev_id;
1457 	int sz, rc;
1458 
1459 	ksmbd_debug(SMB, "authenticate phase\n");
1460 	if (conn->use_spnego) {
1461 		unsigned char *spnego_blob;
1462 		u16 spnego_blob_len;
1463 
1464 		rc = build_spnego_ntlmssp_auth_blob(&spnego_blob,
1465 						    &spnego_blob_len,
1466 						    0);
1467 		if (rc)
1468 			return -ENOMEM;
1469 
1470 		memcpy(rsp->Buffer, spnego_blob, spnego_blob_len);
1471 		rsp->SecurityBufferLength = cpu_to_le16(spnego_blob_len);
1472 		kfree(spnego_blob);
1473 	}
1474 
1475 	user = session_user(conn, req);
1476 	if (!user) {
1477 		ksmbd_debug(SMB, "Unknown user name or an error\n");
1478 		return -EPERM;
1479 	}
1480 
1481 	/* Check for previous session */
1482 	prev_id = le64_to_cpu(req->PreviousSessionId);
1483 	if (prev_id && prev_id != sess->id)
1484 		destroy_previous_session(conn, user, prev_id);
1485 
1486 	if (sess->state == SMB2_SESSION_VALID) {
1487 		/*
1488 		 * Reuse session if anonymous try to connect
1489 		 * on reauthetication.
1490 		 */
1491 		if (conn->binding == false && ksmbd_anonymous_user(user)) {
1492 			ksmbd_free_user(user);
1493 			return 0;
1494 		}
1495 
1496 		if (!ksmbd_compare_user(sess->user, user)) {
1497 			ksmbd_free_user(user);
1498 			return -EPERM;
1499 		}
1500 		ksmbd_free_user(user);
1501 	} else {
1502 		sess->user = user;
1503 	}
1504 
1505 	if (conn->binding == false && user_guest(sess->user)) {
1506 		rsp->SessionFlags = SMB2_SESSION_FLAG_IS_GUEST_LE;
1507 	} else {
1508 		struct authenticate_message *authblob;
1509 
1510 		authblob = user_authblob(conn, req);
1511 		if (conn->use_spnego && conn->mechToken)
1512 			sz = conn->mechTokenLen;
1513 		else
1514 			sz = le16_to_cpu(req->SecurityBufferLength);
1515 		rc = ksmbd_decode_ntlmssp_auth_blob(authblob, sz, conn, sess);
1516 		if (rc) {
1517 			set_user_flag(sess->user, KSMBD_USER_FLAG_BAD_PASSWORD);
1518 			ksmbd_debug(SMB, "authentication failed\n");
1519 			return -EPERM;
1520 		}
1521 	}
1522 
1523 	/*
1524 	 * If session state is SMB2_SESSION_VALID, We can assume
1525 	 * that it is reauthentication. And the user/password
1526 	 * has been verified, so return it here.
1527 	 */
1528 	if (sess->state == SMB2_SESSION_VALID) {
1529 		if (conn->binding)
1530 			goto binding_session;
1531 		return 0;
1532 	}
1533 
1534 	if ((rsp->SessionFlags != SMB2_SESSION_FLAG_IS_GUEST_LE &&
1535 	     (conn->sign || server_conf.enforced_signing)) ||
1536 	    (req->SecurityMode & SMB2_NEGOTIATE_SIGNING_REQUIRED))
1537 		sess->sign = true;
1538 
1539 	if (smb3_encryption_negotiated(conn) &&
1540 			!(req->Flags & SMB2_SESSION_REQ_FLAG_BINDING)) {
1541 		conn->ops->generate_encryptionkey(conn, sess);
1542 		sess->enc = true;
1543 		if (server_conf.flags & KSMBD_GLOBAL_FLAG_SMB2_ENCRYPTION)
1544 			rsp->SessionFlags = SMB2_SESSION_FLAG_ENCRYPT_DATA_LE;
1545 		/*
1546 		 * signing is disable if encryption is enable
1547 		 * on this session
1548 		 */
1549 		sess->sign = false;
1550 	}
1551 
1552 binding_session:
1553 	if (conn->dialect >= SMB30_PROT_ID) {
1554 		chann = lookup_chann_list(sess, conn);
1555 		if (!chann) {
1556 			chann = kmalloc(sizeof(struct channel), KSMBD_DEFAULT_GFP);
1557 			if (!chann)
1558 				return -ENOMEM;
1559 
1560 			chann->conn = conn;
1561 			old = xa_store(&sess->ksmbd_chann_list, (long)conn, chann,
1562 					KSMBD_DEFAULT_GFP);
1563 			if (xa_is_err(old)) {
1564 				kfree(chann);
1565 				return xa_err(old);
1566 			}
1567 		}
1568 	}
1569 
1570 	if (conn->ops->generate_signingkey) {
1571 		rc = conn->ops->generate_signingkey(sess, conn);
1572 		if (rc) {
1573 			ksmbd_debug(SMB, "SMB3 signing key generation failed\n");
1574 			return -EINVAL;
1575 		}
1576 	}
1577 
1578 	if (!ksmbd_conn_lookup_dialect(conn)) {
1579 		pr_err("fail to verify the dialect\n");
1580 		return -ENOENT;
1581 	}
1582 	return 0;
1583 }
1584 
1585 #ifdef CONFIG_SMB_SERVER_KERBEROS5
1586 static int krb5_authenticate(struct ksmbd_work *work,
1587 			     struct smb2_sess_setup_req *req,
1588 			     struct smb2_sess_setup_rsp *rsp)
1589 {
1590 	struct ksmbd_conn *conn = work->conn;
1591 	struct ksmbd_session *sess = work->sess;
1592 	char *in_blob, *out_blob;
1593 	struct channel *chann = NULL, *old;
1594 	u64 prev_sess_id;
1595 	int in_len, out_len;
1596 	int retval;
1597 
1598 	in_blob = (char *)&req->hdr.ProtocolId +
1599 		le16_to_cpu(req->SecurityBufferOffset);
1600 	in_len = le16_to_cpu(req->SecurityBufferLength);
1601 	out_blob = (char *)&rsp->hdr.ProtocolId +
1602 		le16_to_cpu(rsp->SecurityBufferOffset);
1603 	out_len = work->response_sz -
1604 		(le16_to_cpu(rsp->SecurityBufferOffset) + 4);
1605 
1606 	retval = ksmbd_krb5_authenticate(sess, in_blob, in_len,
1607 					 out_blob, &out_len);
1608 	if (retval) {
1609 		ksmbd_debug(SMB, "krb5 authentication failed\n");
1610 		return -EINVAL;
1611 	}
1612 
1613 	/* Check previous session */
1614 	prev_sess_id = le64_to_cpu(req->PreviousSessionId);
1615 	if (prev_sess_id && prev_sess_id != sess->id)
1616 		destroy_previous_session(conn, sess->user, prev_sess_id);
1617 
1618 	rsp->SecurityBufferLength = cpu_to_le16(out_len);
1619 
1620 	/*
1621 	 * If session state is SMB2_SESSION_VALID, We can assume
1622 	 * that it is reauthentication. And the user/password
1623 	 * has been verified, so return it here.
1624 	 */
1625 	if (sess->state == SMB2_SESSION_VALID) {
1626 		if (conn->binding)
1627 			goto binding_session;
1628 		return 0;
1629 	}
1630 
1631 	if ((rsp->SessionFlags != SMB2_SESSION_FLAG_IS_GUEST_LE &&
1632 	    (conn->sign || server_conf.enforced_signing)) ||
1633 	    (req->SecurityMode & SMB2_NEGOTIATE_SIGNING_REQUIRED))
1634 		sess->sign = true;
1635 
1636 	if (smb3_encryption_negotiated(conn) &&
1637 	    !(req->Flags & SMB2_SESSION_REQ_FLAG_BINDING)) {
1638 		conn->ops->generate_encryptionkey(conn, sess);
1639 		sess->enc = true;
1640 		if (server_conf.flags & KSMBD_GLOBAL_FLAG_SMB2_ENCRYPTION)
1641 			rsp->SessionFlags = SMB2_SESSION_FLAG_ENCRYPT_DATA_LE;
1642 		sess->sign = false;
1643 	}
1644 
1645 binding_session:
1646 	if (conn->dialect >= SMB30_PROT_ID) {
1647 		chann = lookup_chann_list(sess, conn);
1648 		if (!chann) {
1649 			chann = kmalloc(sizeof(struct channel), KSMBD_DEFAULT_GFP);
1650 			if (!chann)
1651 				return -ENOMEM;
1652 
1653 			chann->conn = conn;
1654 			old = xa_store(&sess->ksmbd_chann_list, (long)conn,
1655 					chann, KSMBD_DEFAULT_GFP);
1656 			if (xa_is_err(old)) {
1657 				kfree(chann);
1658 				return xa_err(old);
1659 			}
1660 		}
1661 	}
1662 
1663 	if (conn->ops->generate_signingkey) {
1664 		retval = conn->ops->generate_signingkey(sess, conn);
1665 		if (retval) {
1666 			ksmbd_debug(SMB, "SMB3 signing key generation failed\n");
1667 			return -EINVAL;
1668 		}
1669 	}
1670 
1671 	if (!ksmbd_conn_lookup_dialect(conn)) {
1672 		pr_err("fail to verify the dialect\n");
1673 		return -ENOENT;
1674 	}
1675 	return 0;
1676 }
1677 #else
1678 static int krb5_authenticate(struct ksmbd_work *work,
1679 			     struct smb2_sess_setup_req *req,
1680 			     struct smb2_sess_setup_rsp *rsp)
1681 {
1682 	return -EOPNOTSUPP;
1683 }
1684 #endif
1685 
1686 int smb2_sess_setup(struct ksmbd_work *work)
1687 {
1688 	struct ksmbd_conn *conn = work->conn;
1689 	struct smb2_sess_setup_req *req;
1690 	struct smb2_sess_setup_rsp *rsp;
1691 	struct ksmbd_session *sess;
1692 	struct negotiate_message *negblob;
1693 	unsigned int negblob_len, negblob_off;
1694 	int rc = 0;
1695 
1696 	ksmbd_debug(SMB, "Received smb2 session setup request\n");
1697 
1698 	if (!ksmbd_conn_need_setup(conn) && !ksmbd_conn_good(conn)) {
1699 		work->send_no_response = 1;
1700 		return rc;
1701 	}
1702 
1703 	WORK_BUFFERS(work, req, rsp);
1704 
1705 	rsp->StructureSize = cpu_to_le16(9);
1706 	rsp->SessionFlags = 0;
1707 	rsp->SecurityBufferOffset = cpu_to_le16(72);
1708 	rsp->SecurityBufferLength = 0;
1709 
1710 	ksmbd_conn_lock(conn);
1711 	if (!req->hdr.SessionId) {
1712 		sess = ksmbd_smb2_session_create();
1713 		if (!sess) {
1714 			rc = -ENOMEM;
1715 			goto out_err;
1716 		}
1717 		rsp->hdr.SessionId = cpu_to_le64(sess->id);
1718 		rc = ksmbd_session_register(conn, sess);
1719 		if (rc)
1720 			goto out_err;
1721 
1722 		conn->binding = false;
1723 	} else if (conn->dialect >= SMB30_PROT_ID &&
1724 		   (server_conf.flags & KSMBD_GLOBAL_FLAG_SMB3_MULTICHANNEL) &&
1725 		   req->Flags & SMB2_SESSION_REQ_FLAG_BINDING) {
1726 		u64 sess_id = le64_to_cpu(req->hdr.SessionId);
1727 
1728 		sess = ksmbd_session_lookup_slowpath(sess_id);
1729 		if (!sess) {
1730 			rc = -ENOENT;
1731 			goto out_err;
1732 		}
1733 
1734 		if (conn->dialect != sess->dialect) {
1735 			rc = -EINVAL;
1736 			goto out_err;
1737 		}
1738 
1739 		if (!(req->hdr.Flags & SMB2_FLAGS_SIGNED)) {
1740 			rc = -EINVAL;
1741 			goto out_err;
1742 		}
1743 
1744 		if (strncmp(conn->ClientGUID, sess->ClientGUID,
1745 			    SMB2_CLIENT_GUID_SIZE)) {
1746 			rc = -ENOENT;
1747 			goto out_err;
1748 		}
1749 
1750 		if (sess->state == SMB2_SESSION_IN_PROGRESS) {
1751 			rc = -EACCES;
1752 			goto out_err;
1753 		}
1754 
1755 		if (sess->state == SMB2_SESSION_EXPIRED) {
1756 			rc = -EFAULT;
1757 			goto out_err;
1758 		}
1759 
1760 		if (ksmbd_conn_need_reconnect(conn)) {
1761 			rc = -EFAULT;
1762 			ksmbd_user_session_put(sess);
1763 			sess = NULL;
1764 			goto out_err;
1765 		}
1766 
1767 		if (is_ksmbd_session_in_connection(conn, sess_id)) {
1768 			rc = -EACCES;
1769 			goto out_err;
1770 		}
1771 
1772 		if (user_guest(sess->user)) {
1773 			rc = -EOPNOTSUPP;
1774 			goto out_err;
1775 		}
1776 
1777 		conn->binding = true;
1778 	} else if ((conn->dialect < SMB30_PROT_ID ||
1779 		    server_conf.flags & KSMBD_GLOBAL_FLAG_SMB3_MULTICHANNEL) &&
1780 		   (req->Flags & SMB2_SESSION_REQ_FLAG_BINDING)) {
1781 		sess = NULL;
1782 		rc = -EACCES;
1783 		goto out_err;
1784 	} else {
1785 		sess = ksmbd_session_lookup(conn,
1786 					    le64_to_cpu(req->hdr.SessionId));
1787 		if (!sess) {
1788 			rc = -ENOENT;
1789 			goto out_err;
1790 		}
1791 
1792 		if (sess->state == SMB2_SESSION_EXPIRED) {
1793 			rc = -EFAULT;
1794 			goto out_err;
1795 		}
1796 
1797 		if (ksmbd_conn_need_reconnect(conn)) {
1798 			rc = -EFAULT;
1799 			ksmbd_user_session_put(sess);
1800 			sess = NULL;
1801 			goto out_err;
1802 		}
1803 
1804 		conn->binding = false;
1805 	}
1806 	work->sess = sess;
1807 
1808 	negblob_off = le16_to_cpu(req->SecurityBufferOffset);
1809 	negblob_len = le16_to_cpu(req->SecurityBufferLength);
1810 	if (negblob_off < offsetof(struct smb2_sess_setup_req, Buffer)) {
1811 		rc = -EINVAL;
1812 		goto out_err;
1813 	}
1814 
1815 	negblob = (struct negotiate_message *)((char *)&req->hdr.ProtocolId +
1816 			negblob_off);
1817 
1818 	if (decode_negotiation_token(conn, negblob, negblob_len) == 0) {
1819 		if (conn->mechToken) {
1820 			negblob = (struct negotiate_message *)conn->mechToken;
1821 			negblob_len = conn->mechTokenLen;
1822 		}
1823 	}
1824 
1825 	if (negblob_len < offsetof(struct negotiate_message, NegotiateFlags)) {
1826 		rc = -EINVAL;
1827 		goto out_err;
1828 	}
1829 
1830 	if (server_conf.auth_mechs & conn->auth_mechs) {
1831 		rc = generate_preauth_hash(work);
1832 		if (rc)
1833 			goto out_err;
1834 
1835 		if (conn->preferred_auth_mech &
1836 				(KSMBD_AUTH_KRB5 | KSMBD_AUTH_MSKRB5)) {
1837 			rc = krb5_authenticate(work, req, rsp);
1838 			if (rc) {
1839 				rc = -EINVAL;
1840 				goto out_err;
1841 			}
1842 
1843 			if (!ksmbd_conn_need_reconnect(conn)) {
1844 				ksmbd_conn_set_good(conn);
1845 				sess->state = SMB2_SESSION_VALID;
1846 			}
1847 		} else if (conn->preferred_auth_mech == KSMBD_AUTH_NTLMSSP) {
1848 			if (negblob->MessageType == NtLmNegotiate) {
1849 				rc = ntlm_negotiate(work, negblob, negblob_len, rsp);
1850 				if (rc)
1851 					goto out_err;
1852 				rsp->hdr.Status =
1853 					STATUS_MORE_PROCESSING_REQUIRED;
1854 			} else if (negblob->MessageType == NtLmAuthenticate) {
1855 				rc = ntlm_authenticate(work, req, rsp);
1856 				if (rc)
1857 					goto out_err;
1858 
1859 				if (!ksmbd_conn_need_reconnect(conn)) {
1860 					ksmbd_conn_set_good(conn);
1861 					sess->state = SMB2_SESSION_VALID;
1862 				}
1863 				if (conn->binding) {
1864 					struct preauth_session *preauth_sess;
1865 
1866 					preauth_sess =
1867 						ksmbd_preauth_session_lookup(conn, sess->id);
1868 					if (preauth_sess) {
1869 						list_del(&preauth_sess->preauth_entry);
1870 						kfree(preauth_sess);
1871 					}
1872 				}
1873 			} else {
1874 				pr_info_ratelimited("Unknown NTLMSSP message type : 0x%x\n",
1875 						le32_to_cpu(negblob->MessageType));
1876 				rc = -EINVAL;
1877 			}
1878 		} else {
1879 			/* TODO: need one more negotiation */
1880 			pr_err("Not support the preferred authentication\n");
1881 			rc = -EINVAL;
1882 		}
1883 	} else {
1884 		pr_err("Not support authentication\n");
1885 		rc = -EINVAL;
1886 	}
1887 
1888 out_err:
1889 	if (rc == -EINVAL)
1890 		rsp->hdr.Status = STATUS_INVALID_PARAMETER;
1891 	else if (rc == -ENOENT)
1892 		rsp->hdr.Status = STATUS_USER_SESSION_DELETED;
1893 	else if (rc == -EACCES)
1894 		rsp->hdr.Status = STATUS_REQUEST_NOT_ACCEPTED;
1895 	else if (rc == -EFAULT)
1896 		rsp->hdr.Status = STATUS_NETWORK_SESSION_EXPIRED;
1897 	else if (rc == -ENOMEM)
1898 		rsp->hdr.Status = STATUS_INSUFFICIENT_RESOURCES;
1899 	else if (rc == -EOPNOTSUPP)
1900 		rsp->hdr.Status = STATUS_NOT_SUPPORTED;
1901 	else if (rc)
1902 		rsp->hdr.Status = STATUS_LOGON_FAILURE;
1903 
1904 	if (conn->use_spnego && conn->mechToken) {
1905 		kfree(conn->mechToken);
1906 		conn->mechToken = NULL;
1907 	}
1908 
1909 	if (rc < 0) {
1910 		/*
1911 		 * SecurityBufferOffset should be set to zero
1912 		 * in session setup error response.
1913 		 */
1914 		rsp->SecurityBufferOffset = 0;
1915 
1916 		if (sess) {
1917 			bool try_delay = false;
1918 
1919 			/*
1920 			 * To avoid dictionary attacks (repeated session setups rapidly sent) to
1921 			 * connect to server, ksmbd make a delay of a 5 seconds on session setup
1922 			 * failure to make it harder to send enough random connection requests
1923 			 * to break into a server.
1924 			 */
1925 			if (sess->user && sess->user->flags & KSMBD_USER_FLAG_DELAY_SESSION)
1926 				try_delay = true;
1927 
1928 			sess->last_active = jiffies;
1929 			sess->state = SMB2_SESSION_EXPIRED;
1930 			ksmbd_user_session_put(sess);
1931 			work->sess = NULL;
1932 			if (try_delay) {
1933 				ksmbd_conn_set_need_reconnect(conn);
1934 				ssleep(5);
1935 				ksmbd_conn_set_need_setup(conn);
1936 			}
1937 		}
1938 		smb2_set_err_rsp(work);
1939 	} else {
1940 		unsigned int iov_len;
1941 
1942 		if (rsp->SecurityBufferLength)
1943 			iov_len = offsetof(struct smb2_sess_setup_rsp, Buffer) +
1944 				le16_to_cpu(rsp->SecurityBufferLength);
1945 		else
1946 			iov_len = sizeof(struct smb2_sess_setup_rsp);
1947 		rc = ksmbd_iov_pin_rsp(work, rsp, iov_len);
1948 		if (rc)
1949 			rsp->hdr.Status = STATUS_INSUFFICIENT_RESOURCES;
1950 	}
1951 
1952 	ksmbd_conn_unlock(conn);
1953 	return rc;
1954 }
1955 
1956 /**
1957  * smb2_tree_connect() - handler for smb2 tree connect command
1958  * @work:	smb work containing smb request buffer
1959  *
1960  * Return:      0 on success, otherwise error
1961  */
1962 int smb2_tree_connect(struct ksmbd_work *work)
1963 {
1964 	struct ksmbd_conn *conn = work->conn;
1965 	struct smb2_tree_connect_req *req;
1966 	struct smb2_tree_connect_rsp *rsp;
1967 	struct ksmbd_session *sess = work->sess;
1968 	char *treename = NULL, *name = NULL;
1969 	struct ksmbd_tree_conn_status status;
1970 	struct ksmbd_share_config *share = NULL;
1971 	int rc = -EINVAL;
1972 
1973 	ksmbd_debug(SMB, "Received smb2 tree connect request\n");
1974 
1975 	WORK_BUFFERS(work, req, rsp);
1976 
1977 	treename = smb_strndup_from_utf16((char *)req + le16_to_cpu(req->PathOffset),
1978 					  le16_to_cpu(req->PathLength), true,
1979 					  conn->local_nls);
1980 	if (IS_ERR(treename)) {
1981 		pr_err("treename is NULL\n");
1982 		status.ret = KSMBD_TREE_CONN_STATUS_ERROR;
1983 		goto out_err1;
1984 	}
1985 
1986 	name = ksmbd_extract_sharename(conn->um, treename);
1987 	if (IS_ERR(name)) {
1988 		status.ret = KSMBD_TREE_CONN_STATUS_ERROR;
1989 		goto out_err1;
1990 	}
1991 
1992 	ksmbd_debug(SMB, "tree connect request for tree %s treename %s\n",
1993 		    name, treename);
1994 
1995 	status = ksmbd_tree_conn_connect(work, name);
1996 	if (status.ret == KSMBD_TREE_CONN_STATUS_OK)
1997 		rsp->hdr.Id.SyncId.TreeId = cpu_to_le32(status.tree_conn->id);
1998 	else
1999 		goto out_err1;
2000 
2001 	share = status.tree_conn->share_conf;
2002 	if (test_share_config_flag(share, KSMBD_SHARE_FLAG_PIPE)) {
2003 		ksmbd_debug(SMB, "IPC share path request\n");
2004 		rsp->ShareType = SMB2_SHARE_TYPE_PIPE;
2005 		rsp->MaximalAccess = FILE_READ_DATA_LE | FILE_READ_EA_LE |
2006 			FILE_EXECUTE_LE | FILE_READ_ATTRIBUTES_LE |
2007 			FILE_DELETE_LE | FILE_READ_CONTROL_LE |
2008 			FILE_WRITE_DAC_LE | FILE_WRITE_OWNER_LE |
2009 			FILE_SYNCHRONIZE_LE;
2010 	} else {
2011 		rsp->ShareType = SMB2_SHARE_TYPE_DISK;
2012 		rsp->MaximalAccess = FILE_READ_DATA_LE | FILE_READ_EA_LE |
2013 			FILE_EXECUTE_LE | FILE_READ_ATTRIBUTES_LE;
2014 		if (test_tree_conn_flag(status.tree_conn,
2015 					KSMBD_TREE_CONN_FLAG_WRITABLE)) {
2016 			rsp->MaximalAccess |= FILE_WRITE_DATA_LE |
2017 				FILE_APPEND_DATA_LE | FILE_WRITE_EA_LE |
2018 				FILE_DELETE_LE | FILE_WRITE_ATTRIBUTES_LE |
2019 				FILE_DELETE_CHILD_LE | FILE_READ_CONTROL_LE |
2020 				FILE_WRITE_DAC_LE | FILE_WRITE_OWNER_LE |
2021 				FILE_SYNCHRONIZE_LE;
2022 		}
2023 	}
2024 
2025 	status.tree_conn->maximal_access = le32_to_cpu(rsp->MaximalAccess);
2026 	if (conn->posix_ext_supported)
2027 		status.tree_conn->posix_extensions = true;
2028 
2029 	write_lock(&sess->tree_conns_lock);
2030 	status.tree_conn->t_state = TREE_CONNECTED;
2031 	write_unlock(&sess->tree_conns_lock);
2032 	rsp->StructureSize = cpu_to_le16(16);
2033 out_err1:
2034 	if (server_conf.flags & KSMBD_GLOBAL_FLAG_DURABLE_HANDLE && share &&
2035 	    test_share_config_flag(share,
2036 				   KSMBD_SHARE_FLAG_CONTINUOUS_AVAILABILITY))
2037 		rsp->Capabilities = SMB2_SHARE_CAP_CONTINUOUS_AVAILABILITY;
2038 	else
2039 		rsp->Capabilities = 0;
2040 	rsp->Reserved = 0;
2041 	/* default manual caching */
2042 	rsp->ShareFlags = SMB2_SHAREFLAG_MANUAL_CACHING;
2043 
2044 	rc = ksmbd_iov_pin_rsp(work, rsp, sizeof(struct smb2_tree_connect_rsp));
2045 	if (rc)
2046 		status.ret = KSMBD_TREE_CONN_STATUS_NOMEM;
2047 
2048 	if (!IS_ERR(treename))
2049 		kfree(treename);
2050 	if (!IS_ERR(name))
2051 		kfree(name);
2052 
2053 	switch (status.ret) {
2054 	case KSMBD_TREE_CONN_STATUS_OK:
2055 		rsp->hdr.Status = STATUS_SUCCESS;
2056 		rc = 0;
2057 		break;
2058 	case -ESTALE:
2059 	case -ENOENT:
2060 	case KSMBD_TREE_CONN_STATUS_NO_SHARE:
2061 		rsp->hdr.Status = STATUS_BAD_NETWORK_NAME;
2062 		break;
2063 	case -ENOMEM:
2064 	case KSMBD_TREE_CONN_STATUS_NOMEM:
2065 		rsp->hdr.Status = STATUS_NO_MEMORY;
2066 		break;
2067 	case KSMBD_TREE_CONN_STATUS_ERROR:
2068 	case KSMBD_TREE_CONN_STATUS_TOO_MANY_CONNS:
2069 	case KSMBD_TREE_CONN_STATUS_TOO_MANY_SESSIONS:
2070 		rsp->hdr.Status = STATUS_ACCESS_DENIED;
2071 		break;
2072 	case -EINVAL:
2073 		rsp->hdr.Status = STATUS_INVALID_PARAMETER;
2074 		break;
2075 	default:
2076 		rsp->hdr.Status = STATUS_ACCESS_DENIED;
2077 	}
2078 
2079 	if (status.ret != KSMBD_TREE_CONN_STATUS_OK)
2080 		smb2_set_err_rsp(work);
2081 
2082 	return rc;
2083 }
2084 
2085 /**
2086  * smb2_create_open_flags() - convert smb open flags to unix open flags
2087  * @file_present:	is file already present
2088  * @access:		file access flags
2089  * @disposition:	file disposition flags
2090  * @may_flags:		set with MAY_ flags
2091  * @coptions:		file creation options
2092  * @mode:		file mode
2093  *
2094  * Return:      file open flags
2095  */
2096 static int smb2_create_open_flags(bool file_present, __le32 access,
2097 				  __le32 disposition,
2098 				  int *may_flags,
2099 				  __le32 coptions,
2100 				  umode_t mode)
2101 {
2102 	int oflags = O_NONBLOCK | O_LARGEFILE;
2103 
2104 	if (coptions & FILE_DIRECTORY_FILE_LE || S_ISDIR(mode)) {
2105 		access &= ~FILE_WRITE_DESIRE_ACCESS_LE;
2106 		ksmbd_debug(SMB, "Discard write access to a directory\n");
2107 	}
2108 
2109 	if (access & FILE_READ_DESIRED_ACCESS_LE &&
2110 	    access & FILE_WRITE_DESIRE_ACCESS_LE) {
2111 		oflags |= O_RDWR;
2112 		*may_flags = MAY_OPEN | MAY_READ | MAY_WRITE;
2113 	} else if (access & FILE_WRITE_DESIRE_ACCESS_LE) {
2114 		oflags |= O_WRONLY;
2115 		*may_flags = MAY_OPEN | MAY_WRITE;
2116 	} else {
2117 		oflags |= O_RDONLY;
2118 		*may_flags = MAY_OPEN | MAY_READ;
2119 	}
2120 
2121 	if (access == FILE_READ_ATTRIBUTES_LE || S_ISBLK(mode) || S_ISCHR(mode))
2122 		oflags |= O_PATH;
2123 
2124 	if (file_present) {
2125 		switch (disposition & FILE_CREATE_MASK_LE) {
2126 		case FILE_OPEN_LE:
2127 		case FILE_CREATE_LE:
2128 			break;
2129 		case FILE_SUPERSEDE_LE:
2130 		case FILE_OVERWRITE_LE:
2131 		case FILE_OVERWRITE_IF_LE:
2132 			oflags |= O_TRUNC;
2133 			break;
2134 		default:
2135 			break;
2136 		}
2137 	} else {
2138 		switch (disposition & FILE_CREATE_MASK_LE) {
2139 		case FILE_SUPERSEDE_LE:
2140 		case FILE_CREATE_LE:
2141 		case FILE_OPEN_IF_LE:
2142 		case FILE_OVERWRITE_IF_LE:
2143 			oflags |= O_CREAT;
2144 			break;
2145 		case FILE_OPEN_LE:
2146 		case FILE_OVERWRITE_LE:
2147 			oflags &= ~O_CREAT;
2148 			break;
2149 		default:
2150 			break;
2151 		}
2152 	}
2153 
2154 	return oflags;
2155 }
2156 
2157 /**
2158  * smb2_tree_disconnect() - handler for smb tree connect request
2159  * @work:	smb work containing request buffer
2160  *
2161  * Return:      0 on success, otherwise error
2162  */
2163 int smb2_tree_disconnect(struct ksmbd_work *work)
2164 {
2165 	struct smb2_tree_disconnect_rsp *rsp;
2166 	struct smb2_tree_disconnect_req *req;
2167 	struct ksmbd_session *sess = work->sess;
2168 	struct ksmbd_tree_connect *tcon = work->tcon;
2169 	int err;
2170 
2171 	ksmbd_debug(SMB, "Received smb2 tree disconnect request\n");
2172 
2173 	WORK_BUFFERS(work, req, rsp);
2174 
2175 	if (!tcon) {
2176 		ksmbd_debug(SMB, "Invalid tid %d\n", req->hdr.Id.SyncId.TreeId);
2177 
2178 		rsp->hdr.Status = STATUS_NETWORK_NAME_DELETED;
2179 		err = -ENOENT;
2180 		goto err_out;
2181 	}
2182 
2183 	ksmbd_close_tree_conn_fds(work);
2184 
2185 	write_lock(&sess->tree_conns_lock);
2186 	if (tcon->t_state == TREE_DISCONNECTED) {
2187 		write_unlock(&sess->tree_conns_lock);
2188 		rsp->hdr.Status = STATUS_NETWORK_NAME_DELETED;
2189 		err = -ENOENT;
2190 		goto err_out;
2191 	}
2192 
2193 	tcon->t_state = TREE_DISCONNECTED;
2194 	write_unlock(&sess->tree_conns_lock);
2195 
2196 	err = ksmbd_tree_conn_disconnect(sess, tcon);
2197 	if (err) {
2198 		rsp->hdr.Status = STATUS_NETWORK_NAME_DELETED;
2199 		goto err_out;
2200 	}
2201 
2202 	rsp->StructureSize = cpu_to_le16(4);
2203 	err = ksmbd_iov_pin_rsp(work, rsp,
2204 				sizeof(struct smb2_tree_disconnect_rsp));
2205 	if (err) {
2206 		rsp->hdr.Status = STATUS_INSUFFICIENT_RESOURCES;
2207 		goto err_out;
2208 	}
2209 
2210 	return 0;
2211 
2212 err_out:
2213 	smb2_set_err_rsp(work);
2214 	return err;
2215 
2216 }
2217 
2218 /**
2219  * smb2_session_logoff() - handler for session log off request
2220  * @work:	smb work containing request buffer
2221  *
2222  * Return:      0 on success, otherwise error
2223  */
2224 int smb2_session_logoff(struct ksmbd_work *work)
2225 {
2226 	struct ksmbd_conn *conn = work->conn;
2227 	struct ksmbd_session *sess = work->sess;
2228 	struct smb2_logoff_req *req;
2229 	struct smb2_logoff_rsp *rsp;
2230 	u64 sess_id;
2231 	int err;
2232 
2233 	WORK_BUFFERS(work, req, rsp);
2234 
2235 	ksmbd_debug(SMB, "Received smb2 session logoff request\n");
2236 
2237 	ksmbd_conn_lock(conn);
2238 	if (!ksmbd_conn_good(conn)) {
2239 		ksmbd_conn_unlock(conn);
2240 		rsp->hdr.Status = STATUS_NETWORK_NAME_DELETED;
2241 		smb2_set_err_rsp(work);
2242 		return -ENOENT;
2243 	}
2244 	sess_id = le64_to_cpu(req->hdr.SessionId);
2245 	ksmbd_all_conn_set_status(sess_id, KSMBD_SESS_NEED_RECONNECT);
2246 	ksmbd_conn_unlock(conn);
2247 
2248 	ksmbd_close_session_fds(work);
2249 	ksmbd_conn_wait_idle(conn);
2250 
2251 	if (ksmbd_tree_conn_session_logoff(sess)) {
2252 		ksmbd_debug(SMB, "Invalid tid %d\n", req->hdr.Id.SyncId.TreeId);
2253 		rsp->hdr.Status = STATUS_NETWORK_NAME_DELETED;
2254 		smb2_set_err_rsp(work);
2255 		return -ENOENT;
2256 	}
2257 
2258 	down_write(&conn->session_lock);
2259 	sess->state = SMB2_SESSION_EXPIRED;
2260 	up_write(&conn->session_lock);
2261 
2262 	ksmbd_all_conn_set_status(sess_id, KSMBD_SESS_NEED_SETUP);
2263 
2264 	rsp->StructureSize = cpu_to_le16(4);
2265 	err = ksmbd_iov_pin_rsp(work, rsp, sizeof(struct smb2_logoff_rsp));
2266 	if (err) {
2267 		rsp->hdr.Status = STATUS_INSUFFICIENT_RESOURCES;
2268 		smb2_set_err_rsp(work);
2269 		return err;
2270 	}
2271 	return 0;
2272 }
2273 
2274 /**
2275  * create_smb2_pipe() - create IPC pipe
2276  * @work:	smb work containing request buffer
2277  *
2278  * Return:      0 on success, otherwise error
2279  */
2280 static noinline int create_smb2_pipe(struct ksmbd_work *work)
2281 {
2282 	struct smb2_create_rsp *rsp;
2283 	struct smb2_create_req *req;
2284 	int id = -1;
2285 	int err;
2286 	char *name;
2287 
2288 	WORK_BUFFERS(work, req, rsp);
2289 
2290 	name = smb_strndup_from_utf16(req->Buffer, le16_to_cpu(req->NameLength),
2291 				      1, work->conn->local_nls);
2292 	if (IS_ERR(name)) {
2293 		rsp->hdr.Status = STATUS_NO_MEMORY;
2294 		err = PTR_ERR(name);
2295 		goto out;
2296 	}
2297 
2298 	id = ksmbd_session_rpc_open(work->sess, name);
2299 	if (id < 0) {
2300 		pr_err("Unable to open RPC pipe: %d\n", id);
2301 		err = id;
2302 		goto out;
2303 	}
2304 
2305 	rsp->hdr.Status = STATUS_SUCCESS;
2306 	rsp->StructureSize = cpu_to_le16(89);
2307 	rsp->OplockLevel = SMB2_OPLOCK_LEVEL_NONE;
2308 	rsp->Flags = 0;
2309 	rsp->CreateAction = cpu_to_le32(FILE_OPENED);
2310 
2311 	rsp->CreationTime = cpu_to_le64(0);
2312 	rsp->LastAccessTime = cpu_to_le64(0);
2313 	rsp->ChangeTime = cpu_to_le64(0);
2314 	rsp->AllocationSize = cpu_to_le64(0);
2315 	rsp->EndofFile = cpu_to_le64(0);
2316 	rsp->FileAttributes = FILE_ATTRIBUTE_NORMAL_LE;
2317 	rsp->Reserved2 = 0;
2318 	rsp->VolatileFileId = id;
2319 	rsp->PersistentFileId = 0;
2320 	rsp->CreateContextsOffset = 0;
2321 	rsp->CreateContextsLength = 0;
2322 
2323 	err = ksmbd_iov_pin_rsp(work, rsp, offsetof(struct smb2_create_rsp, Buffer));
2324 	if (err)
2325 		goto out;
2326 
2327 	kfree(name);
2328 	return 0;
2329 
2330 out:
2331 	switch (err) {
2332 	case -EINVAL:
2333 		rsp->hdr.Status = STATUS_INVALID_PARAMETER;
2334 		break;
2335 	case -ENOSPC:
2336 	case -ENOMEM:
2337 		rsp->hdr.Status = STATUS_NO_MEMORY;
2338 		break;
2339 	}
2340 
2341 	if (id >= 0)
2342 		ksmbd_session_rpc_close(work->sess, id);
2343 
2344 	if (!IS_ERR(name))
2345 		kfree(name);
2346 
2347 	smb2_set_err_rsp(work);
2348 	return err;
2349 }
2350 
2351 /**
2352  * smb2_set_ea() - handler for setting extended attributes using set
2353  *		info command
2354  * @eabuf:	set info command buffer
2355  * @buf_len:	set info command buffer length
2356  * @path:	dentry path for get ea
2357  * @get_write:	get write access to a mount
2358  *
2359  * Return:	0 on success, otherwise error
2360  */
2361 static int smb2_set_ea(struct smb2_ea_info *eabuf, unsigned int buf_len,
2362 		       const struct path *path, bool get_write)
2363 {
2364 	struct mnt_idmap *idmap = mnt_idmap(path->mnt);
2365 	char *attr_name = NULL, *value;
2366 	int rc = 0;
2367 	unsigned int next = 0;
2368 
2369 	if (buf_len < sizeof(struct smb2_ea_info) + eabuf->EaNameLength + 1 +
2370 			le16_to_cpu(eabuf->EaValueLength))
2371 		return -EINVAL;
2372 
2373 	attr_name = kmalloc(XATTR_NAME_MAX + 1, KSMBD_DEFAULT_GFP);
2374 	if (!attr_name)
2375 		return -ENOMEM;
2376 
2377 	do {
2378 		if (!eabuf->EaNameLength)
2379 			goto next;
2380 
2381 		ksmbd_debug(SMB,
2382 			    "name : <%s>, name_len : %u, value_len : %u, next : %u\n",
2383 			    eabuf->name, eabuf->EaNameLength,
2384 			    le16_to_cpu(eabuf->EaValueLength),
2385 			    le32_to_cpu(eabuf->NextEntryOffset));
2386 
2387 		if (eabuf->EaNameLength >
2388 		    (XATTR_NAME_MAX - XATTR_USER_PREFIX_LEN)) {
2389 			rc = -EINVAL;
2390 			break;
2391 		}
2392 
2393 		memcpy(attr_name, XATTR_USER_PREFIX, XATTR_USER_PREFIX_LEN);
2394 		memcpy(&attr_name[XATTR_USER_PREFIX_LEN], eabuf->name,
2395 		       eabuf->EaNameLength);
2396 		attr_name[XATTR_USER_PREFIX_LEN + eabuf->EaNameLength] = '\0';
2397 		value = (char *)&eabuf->name + eabuf->EaNameLength + 1;
2398 
2399 		if (!eabuf->EaValueLength) {
2400 			rc = ksmbd_vfs_casexattr_len(idmap,
2401 						     path->dentry,
2402 						     attr_name,
2403 						     XATTR_USER_PREFIX_LEN +
2404 						     eabuf->EaNameLength);
2405 
2406 			/* delete the EA only when it exits */
2407 			if (rc > 0) {
2408 				rc = ksmbd_vfs_remove_xattr(idmap,
2409 							    path,
2410 							    attr_name,
2411 							    get_write);
2412 
2413 				if (rc < 0) {
2414 					ksmbd_debug(SMB,
2415 						    "remove xattr failed(%d)\n",
2416 						    rc);
2417 					break;
2418 				}
2419 			}
2420 
2421 			/* if the EA doesn't exist, just do nothing. */
2422 			rc = 0;
2423 		} else {
2424 			rc = ksmbd_vfs_setxattr(idmap, path, attr_name, value,
2425 						le16_to_cpu(eabuf->EaValueLength),
2426 						0, get_write);
2427 			if (rc < 0) {
2428 				ksmbd_debug(SMB,
2429 					    "ksmbd_vfs_setxattr is failed(%d)\n",
2430 					    rc);
2431 				break;
2432 			}
2433 		}
2434 
2435 next:
2436 		next = le32_to_cpu(eabuf->NextEntryOffset);
2437 		if (next == 0 || buf_len < next)
2438 			break;
2439 		buf_len -= next;
2440 		eabuf = (struct smb2_ea_info *)((char *)eabuf + next);
2441 		if (buf_len < sizeof(struct smb2_ea_info)) {
2442 			rc = -EINVAL;
2443 			break;
2444 		}
2445 
2446 		if (buf_len < sizeof(struct smb2_ea_info) + eabuf->EaNameLength + 1 +
2447 				le16_to_cpu(eabuf->EaValueLength)) {
2448 			rc = -EINVAL;
2449 			break;
2450 		}
2451 	} while (next != 0);
2452 
2453 	kfree(attr_name);
2454 	return rc;
2455 }
2456 
2457 static noinline int smb2_set_stream_name_xattr(const struct path *path,
2458 					       struct ksmbd_file *fp,
2459 					       char *stream_name, int s_type)
2460 {
2461 	struct mnt_idmap *idmap = mnt_idmap(path->mnt);
2462 	size_t xattr_stream_size;
2463 	char *xattr_stream_name;
2464 	int rc;
2465 
2466 	rc = ksmbd_vfs_xattr_stream_name(stream_name,
2467 					 &xattr_stream_name,
2468 					 &xattr_stream_size,
2469 					 s_type);
2470 	if (rc)
2471 		return rc;
2472 
2473 	fp->stream.name = xattr_stream_name;
2474 	fp->stream.size = xattr_stream_size;
2475 
2476 	/* Check if there is stream prefix in xattr space */
2477 	rc = ksmbd_vfs_casexattr_len(idmap,
2478 				     path->dentry,
2479 				     xattr_stream_name,
2480 				     xattr_stream_size);
2481 	if (rc >= 0)
2482 		return 0;
2483 
2484 	if (fp->cdoption == FILE_OPEN_LE) {
2485 		ksmbd_debug(SMB, "XATTR stream name lookup failed: %d\n", rc);
2486 		return -EBADF;
2487 	}
2488 
2489 	rc = ksmbd_vfs_setxattr(idmap, path, xattr_stream_name, NULL, 0, 0, false);
2490 	if (rc < 0)
2491 		pr_err("Failed to store XATTR stream name :%d\n", rc);
2492 	return 0;
2493 }
2494 
2495 static int smb2_remove_smb_xattrs(const struct path *path)
2496 {
2497 	struct mnt_idmap *idmap = mnt_idmap(path->mnt);
2498 	char *name, *xattr_list = NULL;
2499 	ssize_t xattr_list_len;
2500 	int err = 0;
2501 
2502 	xattr_list_len = ksmbd_vfs_listxattr(path->dentry, &xattr_list);
2503 	if (xattr_list_len < 0) {
2504 		goto out;
2505 	} else if (!xattr_list_len) {
2506 		ksmbd_debug(SMB, "empty xattr in the file\n");
2507 		goto out;
2508 	}
2509 
2510 	for (name = xattr_list; name - xattr_list < xattr_list_len;
2511 			name += strlen(name) + 1) {
2512 		ksmbd_debug(SMB, "%s, len %zd\n", name, strlen(name));
2513 
2514 		if (!strncmp(name, XATTR_USER_PREFIX, XATTR_USER_PREFIX_LEN) &&
2515 		    !strncmp(&name[XATTR_USER_PREFIX_LEN], STREAM_PREFIX,
2516 			     STREAM_PREFIX_LEN)) {
2517 			err = ksmbd_vfs_remove_xattr(idmap, path,
2518 						     name, true);
2519 			if (err)
2520 				ksmbd_debug(SMB, "remove xattr failed : %s\n",
2521 					    name);
2522 		}
2523 	}
2524 out:
2525 	kvfree(xattr_list);
2526 	return err;
2527 }
2528 
2529 static int smb2_create_truncate(const struct path *path)
2530 {
2531 	int rc = vfs_truncate(path, 0);
2532 
2533 	if (rc) {
2534 		pr_err("vfs_truncate failed, rc %d\n", rc);
2535 		return rc;
2536 	}
2537 
2538 	rc = smb2_remove_smb_xattrs(path);
2539 	if (rc == -EOPNOTSUPP)
2540 		rc = 0;
2541 	if (rc)
2542 		ksmbd_debug(SMB,
2543 			    "ksmbd_truncate_stream_name_xattr failed, rc %d\n",
2544 			    rc);
2545 	return rc;
2546 }
2547 
2548 static void smb2_new_xattrs(struct ksmbd_tree_connect *tcon, const struct path *path,
2549 			    struct ksmbd_file *fp)
2550 {
2551 	struct xattr_dos_attrib da = {0};
2552 	int rc;
2553 
2554 	if (!test_share_config_flag(tcon->share_conf,
2555 				    KSMBD_SHARE_FLAG_STORE_DOS_ATTRS))
2556 		return;
2557 
2558 	da.version = 4;
2559 	da.attr = le32_to_cpu(fp->f_ci->m_fattr);
2560 	da.itime = da.create_time = fp->create_time;
2561 	da.flags = XATTR_DOSINFO_ATTRIB | XATTR_DOSINFO_CREATE_TIME |
2562 		XATTR_DOSINFO_ITIME;
2563 
2564 	rc = ksmbd_vfs_set_dos_attrib_xattr(mnt_idmap(path->mnt), path, &da, true);
2565 	if (rc)
2566 		ksmbd_debug(SMB, "failed to store file attribute into xattr\n");
2567 }
2568 
2569 static void smb2_update_xattrs(struct ksmbd_tree_connect *tcon,
2570 			       const struct path *path, struct ksmbd_file *fp)
2571 {
2572 	struct xattr_dos_attrib da;
2573 	int rc;
2574 
2575 	fp->f_ci->m_fattr &= ~(FILE_ATTRIBUTE_HIDDEN_LE | FILE_ATTRIBUTE_SYSTEM_LE);
2576 
2577 	/* get FileAttributes from XATTR_NAME_DOS_ATTRIBUTE */
2578 	if (!test_share_config_flag(tcon->share_conf,
2579 				    KSMBD_SHARE_FLAG_STORE_DOS_ATTRS))
2580 		return;
2581 
2582 	rc = ksmbd_vfs_get_dos_attrib_xattr(mnt_idmap(path->mnt),
2583 					    path->dentry, &da);
2584 	if (rc > 0) {
2585 		fp->f_ci->m_fattr = cpu_to_le32(da.attr);
2586 		fp->create_time = da.create_time;
2587 		fp->itime = da.itime;
2588 	}
2589 }
2590 
2591 static int smb2_creat(struct ksmbd_work *work,
2592 		      struct path *path, char *name, int open_flags,
2593 		      umode_t posix_mode, bool is_dir)
2594 {
2595 	struct ksmbd_tree_connect *tcon = work->tcon;
2596 	struct ksmbd_share_config *share = tcon->share_conf;
2597 	umode_t mode;
2598 	int rc;
2599 
2600 	if (!(open_flags & O_CREAT))
2601 		return -EBADF;
2602 
2603 	ksmbd_debug(SMB, "file does not exist, so creating\n");
2604 	if (is_dir == true) {
2605 		ksmbd_debug(SMB, "creating directory\n");
2606 
2607 		mode = share_config_directory_mode(share, posix_mode);
2608 		rc = ksmbd_vfs_mkdir(work, name, mode);
2609 		if (rc)
2610 			return rc;
2611 	} else {
2612 		ksmbd_debug(SMB, "creating regular file\n");
2613 
2614 		mode = share_config_create_mode(share, posix_mode);
2615 		rc = ksmbd_vfs_create(work, name, mode);
2616 		if (rc)
2617 			return rc;
2618 	}
2619 
2620 	rc = ksmbd_vfs_kern_path(work, name, 0, path, 0);
2621 	if (rc) {
2622 		pr_err("cannot get linux path (%s), err = %d\n",
2623 		       name, rc);
2624 		return rc;
2625 	}
2626 	return 0;
2627 }
2628 
2629 static int smb2_create_sd_buffer(struct ksmbd_work *work,
2630 				 struct smb2_create_req *req,
2631 				 const struct path *path)
2632 {
2633 	struct create_context *context;
2634 	struct create_sd_buf_req *sd_buf;
2635 
2636 	if (!req->CreateContextsOffset)
2637 		return -ENOENT;
2638 
2639 	/* Parse SD BUFFER create contexts */
2640 	context = smb2_find_context_vals(req, SMB2_CREATE_SD_BUFFER, 4);
2641 	if (!context)
2642 		return -ENOENT;
2643 	else if (IS_ERR(context))
2644 		return PTR_ERR(context);
2645 
2646 	ksmbd_debug(SMB,
2647 		    "Set ACLs using SMB2_CREATE_SD_BUFFER context\n");
2648 	sd_buf = (struct create_sd_buf_req *)context;
2649 	if (le16_to_cpu(context->DataOffset) +
2650 	    le32_to_cpu(context->DataLength) <
2651 	    sizeof(struct create_sd_buf_req))
2652 		return -EINVAL;
2653 	return set_info_sec(work->conn, work->tcon, path, &sd_buf->ntsd,
2654 			    le32_to_cpu(sd_buf->ccontext.DataLength), true, false);
2655 }
2656 
2657 static void ksmbd_acls_fattr(struct smb_fattr *fattr,
2658 			     struct mnt_idmap *idmap,
2659 			     struct inode *inode)
2660 {
2661 	vfsuid_t vfsuid = i_uid_into_vfsuid(idmap, inode);
2662 	vfsgid_t vfsgid = i_gid_into_vfsgid(idmap, inode);
2663 
2664 	fattr->cf_uid = vfsuid_into_kuid(vfsuid);
2665 	fattr->cf_gid = vfsgid_into_kgid(vfsgid);
2666 	fattr->cf_mode = inode->i_mode;
2667 	fattr->cf_acls = NULL;
2668 	fattr->cf_dacls = NULL;
2669 
2670 	if (IS_ENABLED(CONFIG_FS_POSIX_ACL)) {
2671 		fattr->cf_acls = get_inode_acl(inode, ACL_TYPE_ACCESS);
2672 		if (S_ISDIR(inode->i_mode))
2673 			fattr->cf_dacls = get_inode_acl(inode, ACL_TYPE_DEFAULT);
2674 	}
2675 }
2676 
2677 enum {
2678 	DURABLE_RECONN_V2 = 1,
2679 	DURABLE_RECONN,
2680 	DURABLE_REQ_V2,
2681 	DURABLE_REQ,
2682 };
2683 
2684 struct durable_info {
2685 	struct ksmbd_file *fp;
2686 	unsigned short int type;
2687 	bool persistent;
2688 	bool reconnected;
2689 	unsigned int timeout;
2690 	char *CreateGuid;
2691 };
2692 
2693 static int parse_durable_handle_context(struct ksmbd_work *work,
2694 					struct smb2_create_req *req,
2695 					struct lease_ctx_info *lc,
2696 					struct durable_info *dh_info)
2697 {
2698 	struct ksmbd_conn *conn = work->conn;
2699 	struct create_context *context;
2700 	int dh_idx, err = 0;
2701 	u64 persistent_id = 0;
2702 	int req_op_level;
2703 	static const char * const durable_arr[] = {"DH2C", "DHnC", "DH2Q", "DHnQ"};
2704 
2705 	req_op_level = req->RequestedOplockLevel;
2706 	for (dh_idx = DURABLE_RECONN_V2; dh_idx <= ARRAY_SIZE(durable_arr);
2707 	     dh_idx++) {
2708 		context = smb2_find_context_vals(req, durable_arr[dh_idx - 1], 4);
2709 		if (IS_ERR(context)) {
2710 			err = PTR_ERR(context);
2711 			goto out;
2712 		}
2713 		if (!context)
2714 			continue;
2715 
2716 		switch (dh_idx) {
2717 		case DURABLE_RECONN_V2:
2718 		{
2719 			struct create_durable_handle_reconnect_v2 *recon_v2;
2720 
2721 			if (dh_info->type == DURABLE_RECONN ||
2722 			    dh_info->type == DURABLE_REQ_V2) {
2723 				err = -EINVAL;
2724 				goto out;
2725 			}
2726 
2727 			if (le16_to_cpu(context->DataOffset) +
2728 				le32_to_cpu(context->DataLength) <
2729 			    sizeof(struct create_durable_handle_reconnect_v2)) {
2730 				err = -EINVAL;
2731 				goto out;
2732 			}
2733 
2734 			recon_v2 = (struct create_durable_handle_reconnect_v2 *)context;
2735 			persistent_id = recon_v2->dcontext.Fid.PersistentFileId;
2736 			dh_info->fp = ksmbd_lookup_durable_fd(persistent_id);
2737 			if (!dh_info->fp) {
2738 				ksmbd_debug(SMB, "Failed to get durable handle state\n");
2739 				err = -EBADF;
2740 				goto out;
2741 			}
2742 
2743 			if (memcmp(dh_info->fp->create_guid, recon_v2->dcontext.CreateGuid,
2744 				   SMB2_CREATE_GUID_SIZE)) {
2745 				err = -EBADF;
2746 				ksmbd_put_durable_fd(dh_info->fp);
2747 				goto out;
2748 			}
2749 
2750 			dh_info->type = dh_idx;
2751 			dh_info->reconnected = true;
2752 			ksmbd_debug(SMB,
2753 				"reconnect v2 Persistent-id from reconnect = %llu\n",
2754 					persistent_id);
2755 			break;
2756 		}
2757 		case DURABLE_RECONN:
2758 		{
2759 			create_durable_reconn_t *recon;
2760 
2761 			if (dh_info->type == DURABLE_RECONN_V2 ||
2762 			    dh_info->type == DURABLE_REQ_V2) {
2763 				err = -EINVAL;
2764 				goto out;
2765 			}
2766 
2767 			if (le16_to_cpu(context->DataOffset) +
2768 				le32_to_cpu(context->DataLength) <
2769 			    sizeof(create_durable_reconn_t)) {
2770 				err = -EINVAL;
2771 				goto out;
2772 			}
2773 
2774 			recon = (create_durable_reconn_t *)context;
2775 			persistent_id = recon->Data.Fid.PersistentFileId;
2776 			dh_info->fp = ksmbd_lookup_durable_fd(persistent_id);
2777 			if (!dh_info->fp) {
2778 				ksmbd_debug(SMB, "Failed to get durable handle state\n");
2779 				err = -EBADF;
2780 				goto out;
2781 			}
2782 
2783 			dh_info->type = dh_idx;
2784 			dh_info->reconnected = true;
2785 			ksmbd_debug(SMB, "reconnect Persistent-id from reconnect = %llu\n",
2786 				    persistent_id);
2787 			break;
2788 		}
2789 		case DURABLE_REQ_V2:
2790 		{
2791 			struct create_durable_req_v2 *durable_v2_blob;
2792 
2793 			if (dh_info->type == DURABLE_RECONN ||
2794 			    dh_info->type == DURABLE_RECONN_V2) {
2795 				err = -EINVAL;
2796 				goto out;
2797 			}
2798 
2799 			if (le16_to_cpu(context->DataOffset) +
2800 				le32_to_cpu(context->DataLength) <
2801 			    sizeof(struct create_durable_req_v2)) {
2802 				err = -EINVAL;
2803 				goto out;
2804 			}
2805 
2806 			durable_v2_blob =
2807 				(struct create_durable_req_v2 *)context;
2808 			ksmbd_debug(SMB, "Request for durable v2 open\n");
2809 			dh_info->fp = ksmbd_lookup_fd_cguid(durable_v2_blob->dcontext.CreateGuid);
2810 			if (dh_info->fp) {
2811 				if (!memcmp(conn->ClientGUID, dh_info->fp->client_guid,
2812 					    SMB2_CLIENT_GUID_SIZE)) {
2813 					if (!(req->hdr.Flags & SMB2_FLAGS_REPLAY_OPERATION)) {
2814 						err = -ENOEXEC;
2815 						ksmbd_put_durable_fd(dh_info->fp);
2816 						goto out;
2817 					}
2818 
2819 					dh_info->fp->conn = conn;
2820 					dh_info->reconnected = true;
2821 					goto out;
2822 				}
2823 			}
2824 
2825 			if ((lc && (lc->req_state & SMB2_LEASE_HANDLE_CACHING_LE)) ||
2826 			    req_op_level == SMB2_OPLOCK_LEVEL_BATCH) {
2827 				dh_info->CreateGuid =
2828 					durable_v2_blob->dcontext.CreateGuid;
2829 				dh_info->persistent =
2830 					le32_to_cpu(durable_v2_blob->dcontext.Flags);
2831 				dh_info->timeout =
2832 					le32_to_cpu(durable_v2_blob->dcontext.Timeout);
2833 				dh_info->type = dh_idx;
2834 			}
2835 			break;
2836 		}
2837 		case DURABLE_REQ:
2838 			if (dh_info->type == DURABLE_RECONN)
2839 				goto out;
2840 			if (dh_info->type == DURABLE_RECONN_V2 ||
2841 			    dh_info->type == DURABLE_REQ_V2) {
2842 				err = -EINVAL;
2843 				goto out;
2844 			}
2845 
2846 			if ((lc && (lc->req_state & SMB2_LEASE_HANDLE_CACHING_LE)) ||
2847 			    req_op_level == SMB2_OPLOCK_LEVEL_BATCH) {
2848 				ksmbd_debug(SMB, "Request for durable open\n");
2849 				dh_info->type = dh_idx;
2850 			}
2851 		}
2852 	}
2853 
2854 out:
2855 	return err;
2856 }
2857 
2858 /**
2859  * smb2_open() - handler for smb file open request
2860  * @work:	smb work containing request buffer
2861  *
2862  * Return:      0 on success, otherwise error
2863  */
2864 int smb2_open(struct ksmbd_work *work)
2865 {
2866 	struct ksmbd_conn *conn = work->conn;
2867 	struct ksmbd_session *sess = work->sess;
2868 	struct ksmbd_tree_connect *tcon = work->tcon;
2869 	struct smb2_create_req *req;
2870 	struct smb2_create_rsp *rsp;
2871 	struct path path;
2872 	struct ksmbd_share_config *share = tcon->share_conf;
2873 	struct ksmbd_file *fp = NULL;
2874 	struct file *filp = NULL;
2875 	struct mnt_idmap *idmap = NULL;
2876 	struct kstat stat;
2877 	struct create_context *context;
2878 	struct lease_ctx_info *lc = NULL;
2879 	struct create_ea_buf_req *ea_buf = NULL;
2880 	struct oplock_info *opinfo;
2881 	struct durable_info dh_info = {0};
2882 	__le32 *next_ptr = NULL;
2883 	int req_op_level = 0, open_flags = 0, may_flags = 0, file_info = 0;
2884 	int rc = 0;
2885 	int contxt_cnt = 0, query_disk_id = 0;
2886 	bool maximal_access_ctxt = false, posix_ctxt = false;
2887 	int s_type = 0;
2888 	int next_off = 0;
2889 	char *name = NULL;
2890 	char *stream_name = NULL;
2891 	bool file_present = false, created = false, already_permitted = false;
2892 	int share_ret, need_truncate = 0;
2893 	u64 time;
2894 	umode_t posix_mode = 0;
2895 	__le32 daccess, maximal_access = 0;
2896 	int iov_len = 0;
2897 
2898 	ksmbd_debug(SMB, "Received smb2 create request\n");
2899 
2900 	WORK_BUFFERS(work, req, rsp);
2901 
2902 	if (req->hdr.NextCommand && !work->next_smb2_rcv_hdr_off &&
2903 	    (req->hdr.Flags & SMB2_FLAGS_RELATED_OPERATIONS)) {
2904 		ksmbd_debug(SMB, "invalid flag in chained command\n");
2905 		rsp->hdr.Status = STATUS_INVALID_PARAMETER;
2906 		smb2_set_err_rsp(work);
2907 		return -EINVAL;
2908 	}
2909 
2910 	if (test_share_config_flag(share, KSMBD_SHARE_FLAG_PIPE)) {
2911 		ksmbd_debug(SMB, "IPC pipe create request\n");
2912 		return create_smb2_pipe(work);
2913 	}
2914 
2915 	if (req->CreateContextsOffset && tcon->posix_extensions) {
2916 		context = smb2_find_context_vals(req, SMB2_CREATE_TAG_POSIX, 16);
2917 		if (IS_ERR(context)) {
2918 			rc = PTR_ERR(context);
2919 			goto err_out2;
2920 		} else if (context) {
2921 			struct create_posix *posix = (struct create_posix *)context;
2922 
2923 			if (le16_to_cpu(context->DataOffset) +
2924 				le32_to_cpu(context->DataLength) <
2925 			    sizeof(struct create_posix) - 4) {
2926 				rc = -EINVAL;
2927 				goto err_out2;
2928 			}
2929 			ksmbd_debug(SMB, "get posix context\n");
2930 
2931 			posix_mode = le32_to_cpu(posix->Mode);
2932 			posix_ctxt = true;
2933 		}
2934 	}
2935 
2936 	if (req->NameLength) {
2937 		name = smb2_get_name((char *)req + le16_to_cpu(req->NameOffset),
2938 				     le16_to_cpu(req->NameLength),
2939 				     work->conn->local_nls);
2940 		if (IS_ERR(name)) {
2941 			rc = PTR_ERR(name);
2942 			name = NULL;
2943 			goto err_out2;
2944 		}
2945 
2946 		ksmbd_debug(SMB, "converted name = %s\n", name);
2947 
2948 		if (posix_ctxt == false) {
2949 			if (strchr(name, ':')) {
2950 				if (!test_share_config_flag(work->tcon->share_conf,
2951 							KSMBD_SHARE_FLAG_STREAMS)) {
2952 					rc = -EBADF;
2953 					goto err_out2;
2954 				}
2955 				rc = parse_stream_name(name, &stream_name, &s_type);
2956 				if (rc < 0)
2957 					goto err_out2;
2958 			}
2959 
2960 			rc = ksmbd_validate_filename(name);
2961 			if (rc < 0)
2962 				goto err_out2;
2963 		}
2964 
2965 		if (ksmbd_share_veto_filename(share, name)) {
2966 			rc = -ENOENT;
2967 			ksmbd_debug(SMB, "Reject open(), vetoed file: %s\n",
2968 				    name);
2969 			goto err_out2;
2970 		}
2971 	} else {
2972 		name = kstrdup("", KSMBD_DEFAULT_GFP);
2973 		if (!name) {
2974 			rc = -ENOMEM;
2975 			goto err_out2;
2976 		}
2977 	}
2978 
2979 	req_op_level = req->RequestedOplockLevel;
2980 
2981 	if (server_conf.flags & KSMBD_GLOBAL_FLAG_DURABLE_HANDLE &&
2982 	    req->CreateContextsOffset) {
2983 		lc = parse_lease_state(req);
2984 		rc = parse_durable_handle_context(work, req, lc, &dh_info);
2985 		if (rc) {
2986 			ksmbd_debug(SMB, "error parsing durable handle context\n");
2987 			goto err_out2;
2988 		}
2989 
2990 		if (dh_info.reconnected == true) {
2991 			rc = smb2_check_durable_oplock(conn, share, dh_info.fp, lc, name);
2992 			if (rc) {
2993 				ksmbd_put_durable_fd(dh_info.fp);
2994 				goto err_out2;
2995 			}
2996 
2997 			rc = ksmbd_reopen_durable_fd(work, dh_info.fp);
2998 			if (rc) {
2999 				ksmbd_put_durable_fd(dh_info.fp);
3000 				goto err_out2;
3001 			}
3002 
3003 			if (ksmbd_override_fsids(work)) {
3004 				rc = -ENOMEM;
3005 				ksmbd_put_durable_fd(dh_info.fp);
3006 				goto err_out2;
3007 			}
3008 
3009 			fp = dh_info.fp;
3010 			file_info = FILE_OPENED;
3011 
3012 			rc = ksmbd_vfs_getattr(&fp->filp->f_path, &stat);
3013 			ksmbd_put_durable_fd(fp);
3014 			if (rc)
3015 				goto err_out2;
3016 
3017 			goto reconnected_fp;
3018 		}
3019 	} else if (req_op_level == SMB2_OPLOCK_LEVEL_LEASE)
3020 		lc = parse_lease_state(req);
3021 
3022 	if (le32_to_cpu(req->ImpersonationLevel) > le32_to_cpu(IL_DELEGATE)) {
3023 		pr_err("Invalid impersonationlevel : 0x%x\n",
3024 		       le32_to_cpu(req->ImpersonationLevel));
3025 		rc = -EIO;
3026 		rsp->hdr.Status = STATUS_BAD_IMPERSONATION_LEVEL;
3027 		goto err_out2;
3028 	}
3029 
3030 	if (req->CreateOptions && !(req->CreateOptions & CREATE_OPTIONS_MASK_LE)) {
3031 		pr_err("Invalid create options : 0x%x\n",
3032 		       le32_to_cpu(req->CreateOptions));
3033 		rc = -EINVAL;
3034 		goto err_out2;
3035 	} else {
3036 		if (req->CreateOptions & FILE_SEQUENTIAL_ONLY_LE &&
3037 		    req->CreateOptions & FILE_RANDOM_ACCESS_LE)
3038 			req->CreateOptions = ~(FILE_SEQUENTIAL_ONLY_LE);
3039 
3040 		if (req->CreateOptions &
3041 		    (FILE_OPEN_BY_FILE_ID_LE | CREATE_TREE_CONNECTION |
3042 		     FILE_RESERVE_OPFILTER_LE)) {
3043 			rc = -EOPNOTSUPP;
3044 			goto err_out2;
3045 		}
3046 
3047 		if (req->CreateOptions & FILE_DIRECTORY_FILE_LE) {
3048 			if (req->CreateOptions & FILE_NON_DIRECTORY_FILE_LE) {
3049 				rc = -EINVAL;
3050 				goto err_out2;
3051 			} else if (req->CreateOptions & FILE_NO_COMPRESSION_LE) {
3052 				req->CreateOptions = ~(FILE_NO_COMPRESSION_LE);
3053 			}
3054 		}
3055 	}
3056 
3057 	if (le32_to_cpu(req->CreateDisposition) >
3058 	    le32_to_cpu(FILE_OVERWRITE_IF_LE)) {
3059 		pr_err("Invalid create disposition : 0x%x\n",
3060 		       le32_to_cpu(req->CreateDisposition));
3061 		rc = -EINVAL;
3062 		goto err_out2;
3063 	}
3064 
3065 	if (!(req->DesiredAccess & DESIRED_ACCESS_MASK)) {
3066 		pr_err("Invalid desired access : 0x%x\n",
3067 		       le32_to_cpu(req->DesiredAccess));
3068 		rc = -EACCES;
3069 		goto err_out2;
3070 	}
3071 
3072 	if (req->FileAttributes && !(req->FileAttributes & FILE_ATTRIBUTE_MASK_LE)) {
3073 		pr_err("Invalid file attribute : 0x%x\n",
3074 		       le32_to_cpu(req->FileAttributes));
3075 		rc = -EINVAL;
3076 		goto err_out2;
3077 	}
3078 
3079 	if (req->CreateContextsOffset) {
3080 		/* Parse non-durable handle create contexts */
3081 		context = smb2_find_context_vals(req, SMB2_CREATE_EA_BUFFER, 4);
3082 		if (IS_ERR(context)) {
3083 			rc = PTR_ERR(context);
3084 			goto err_out2;
3085 		} else if (context) {
3086 			ea_buf = (struct create_ea_buf_req *)context;
3087 			if (le16_to_cpu(context->DataOffset) +
3088 			    le32_to_cpu(context->DataLength) <
3089 			    sizeof(struct create_ea_buf_req)) {
3090 				rc = -EINVAL;
3091 				goto err_out2;
3092 			}
3093 			if (req->CreateOptions & FILE_NO_EA_KNOWLEDGE_LE) {
3094 				rsp->hdr.Status = STATUS_ACCESS_DENIED;
3095 				rc = -EACCES;
3096 				goto err_out2;
3097 			}
3098 		}
3099 
3100 		context = smb2_find_context_vals(req,
3101 						 SMB2_CREATE_QUERY_MAXIMAL_ACCESS_REQUEST, 4);
3102 		if (IS_ERR(context)) {
3103 			rc = PTR_ERR(context);
3104 			goto err_out2;
3105 		} else if (context) {
3106 			ksmbd_debug(SMB,
3107 				    "get query maximal access context\n");
3108 			maximal_access_ctxt = 1;
3109 		}
3110 
3111 		context = smb2_find_context_vals(req,
3112 						 SMB2_CREATE_TIMEWARP_REQUEST, 4);
3113 		if (IS_ERR(context)) {
3114 			rc = PTR_ERR(context);
3115 			goto err_out2;
3116 		} else if (context) {
3117 			ksmbd_debug(SMB, "get timewarp context\n");
3118 			rc = -EBADF;
3119 			goto err_out2;
3120 		}
3121 	}
3122 
3123 	if (ksmbd_override_fsids(work)) {
3124 		rc = -ENOMEM;
3125 		goto err_out2;
3126 	}
3127 
3128 	rc = ksmbd_vfs_kern_path(work, name, LOOKUP_NO_SYMLINKS,
3129 				 &path, 1);
3130 	if (!rc) {
3131 		file_present = true;
3132 
3133 		if (req->CreateOptions & FILE_DELETE_ON_CLOSE_LE) {
3134 			/*
3135 			 * If file exists with under flags, return access
3136 			 * denied error.
3137 			 */
3138 			if (req->CreateDisposition == FILE_OVERWRITE_IF_LE ||
3139 			    req->CreateDisposition == FILE_OPEN_IF_LE) {
3140 				rc = -EACCES;
3141 				goto err_out;
3142 			}
3143 
3144 			if (!test_tree_conn_flag(tcon, KSMBD_TREE_CONN_FLAG_WRITABLE)) {
3145 				ksmbd_debug(SMB,
3146 					    "User does not have write permission\n");
3147 				rc = -EACCES;
3148 				goto err_out;
3149 			}
3150 		} else if (d_is_symlink(path.dentry)) {
3151 			rc = -EACCES;
3152 			goto err_out;
3153 		}
3154 
3155 		idmap = mnt_idmap(path.mnt);
3156 	} else {
3157 		if (rc != -ENOENT)
3158 			goto err_out;
3159 		ksmbd_debug(SMB, "can not get linux path for %s, rc = %d\n",
3160 			    name, rc);
3161 		rc = 0;
3162 	}
3163 
3164 	if (stream_name) {
3165 		if (req->CreateOptions & FILE_DIRECTORY_FILE_LE) {
3166 			if (s_type == DATA_STREAM) {
3167 				rc = -EIO;
3168 				rsp->hdr.Status = STATUS_NOT_A_DIRECTORY;
3169 			}
3170 		} else {
3171 			if (file_present && S_ISDIR(d_inode(path.dentry)->i_mode) &&
3172 			    s_type == DATA_STREAM) {
3173 				rc = -EIO;
3174 				rsp->hdr.Status = STATUS_FILE_IS_A_DIRECTORY;
3175 			}
3176 		}
3177 
3178 		if (req->CreateOptions & FILE_DIRECTORY_FILE_LE &&
3179 		    req->FileAttributes & FILE_ATTRIBUTE_NORMAL_LE) {
3180 			rsp->hdr.Status = STATUS_NOT_A_DIRECTORY;
3181 			rc = -EIO;
3182 		}
3183 
3184 		if (rc < 0)
3185 			goto err_out;
3186 	}
3187 
3188 	if (file_present && req->CreateOptions & FILE_NON_DIRECTORY_FILE_LE &&
3189 	    S_ISDIR(d_inode(path.dentry)->i_mode) &&
3190 	    !(req->CreateOptions & FILE_DELETE_ON_CLOSE_LE)) {
3191 		ksmbd_debug(SMB, "open() argument is a directory: %s, %x\n",
3192 			    name, req->CreateOptions);
3193 		rsp->hdr.Status = STATUS_FILE_IS_A_DIRECTORY;
3194 		rc = -EIO;
3195 		goto err_out;
3196 	}
3197 
3198 	if (file_present && (req->CreateOptions & FILE_DIRECTORY_FILE_LE) &&
3199 	    !(req->CreateDisposition == FILE_CREATE_LE) &&
3200 	    !S_ISDIR(d_inode(path.dentry)->i_mode)) {
3201 		rsp->hdr.Status = STATUS_NOT_A_DIRECTORY;
3202 		rc = -EIO;
3203 		goto err_out;
3204 	}
3205 
3206 	if (!stream_name && file_present &&
3207 	    req->CreateDisposition == FILE_CREATE_LE) {
3208 		rc = -EEXIST;
3209 		goto err_out;
3210 	}
3211 
3212 	daccess = smb_map_generic_desired_access(req->DesiredAccess);
3213 
3214 	if (file_present && !(req->CreateOptions & FILE_DELETE_ON_CLOSE_LE)) {
3215 		rc = smb_check_perm_dacl(conn, &path, &daccess,
3216 					 sess->user->uid);
3217 		if (rc)
3218 			goto err_out;
3219 	}
3220 
3221 	if (daccess & FILE_MAXIMAL_ACCESS_LE) {
3222 		if (!file_present) {
3223 			daccess = cpu_to_le32(GENERIC_ALL_FLAGS);
3224 		} else {
3225 			ksmbd_vfs_query_maximal_access(idmap,
3226 							    path.dentry,
3227 							    &daccess);
3228 			already_permitted = true;
3229 		}
3230 		maximal_access = daccess;
3231 	}
3232 
3233 	open_flags = smb2_create_open_flags(file_present, daccess,
3234 					    req->CreateDisposition,
3235 					    &may_flags,
3236 					    req->CreateOptions,
3237 					    file_present ? d_inode(path.dentry)->i_mode : 0);
3238 
3239 	if (!test_tree_conn_flag(tcon, KSMBD_TREE_CONN_FLAG_WRITABLE)) {
3240 		if (open_flags & (O_CREAT | O_TRUNC)) {
3241 			ksmbd_debug(SMB,
3242 				    "User does not have write permission\n");
3243 			rc = -EACCES;
3244 			goto err_out;
3245 		}
3246 	}
3247 
3248 	/*create file if not present */
3249 	if (!file_present) {
3250 		rc = smb2_creat(work, &path, name, open_flags,
3251 				posix_mode,
3252 				req->CreateOptions & FILE_DIRECTORY_FILE_LE);
3253 		if (rc) {
3254 			if (rc == -ENOENT) {
3255 				rc = -EIO;
3256 				rsp->hdr.Status = STATUS_OBJECT_PATH_NOT_FOUND;
3257 			}
3258 			goto err_out;
3259 		}
3260 
3261 		created = true;
3262 		idmap = mnt_idmap(path.mnt);
3263 		if (ea_buf) {
3264 			if (le32_to_cpu(ea_buf->ccontext.DataLength) <
3265 			    sizeof(struct smb2_ea_info)) {
3266 				rc = -EINVAL;
3267 				goto err_out;
3268 			}
3269 
3270 			rc = smb2_set_ea(&ea_buf->ea,
3271 					 le32_to_cpu(ea_buf->ccontext.DataLength),
3272 					 &path, false);
3273 			if (rc == -EOPNOTSUPP)
3274 				rc = 0;
3275 			else if (rc)
3276 				goto err_out;
3277 		}
3278 	} else if (!already_permitted) {
3279 		/* FILE_READ_ATTRIBUTE is allowed without inode_permission,
3280 		 * because execute(search) permission on a parent directory,
3281 		 * is already granted.
3282 		 */
3283 		if (daccess & ~(FILE_READ_ATTRIBUTES_LE | FILE_READ_CONTROL_LE)) {
3284 			rc = inode_permission(idmap,
3285 					      d_inode(path.dentry),
3286 					      may_flags);
3287 			if (rc)
3288 				goto err_out;
3289 
3290 			if ((daccess & FILE_DELETE_LE) ||
3291 			    (req->CreateOptions & FILE_DELETE_ON_CLOSE_LE)) {
3292 				rc = inode_permission(idmap,
3293 						      d_inode(path.dentry->d_parent),
3294 						      MAY_EXEC | MAY_WRITE);
3295 				if (rc)
3296 					goto err_out;
3297 			}
3298 		}
3299 	}
3300 
3301 	rc = ksmbd_query_inode_status(path.dentry->d_parent);
3302 	if (rc == KSMBD_INODE_STATUS_PENDING_DELETE) {
3303 		rc = -EBUSY;
3304 		goto err_out;
3305 	}
3306 
3307 	rc = 0;
3308 	filp = dentry_open(&path, open_flags, current_cred());
3309 	if (IS_ERR(filp)) {
3310 		rc = PTR_ERR(filp);
3311 		pr_err("dentry open for dir failed, rc %d\n", rc);
3312 		goto err_out;
3313 	}
3314 
3315 	if (file_present) {
3316 		if (!(open_flags & O_TRUNC))
3317 			file_info = FILE_OPENED;
3318 		else
3319 			file_info = FILE_OVERWRITTEN;
3320 
3321 		if ((req->CreateDisposition & FILE_CREATE_MASK_LE) ==
3322 		    FILE_SUPERSEDE_LE)
3323 			file_info = FILE_SUPERSEDED;
3324 	} else if (open_flags & O_CREAT) {
3325 		file_info = FILE_CREATED;
3326 	}
3327 
3328 	ksmbd_vfs_set_fadvise(filp, req->CreateOptions);
3329 
3330 	/* Obtain Volatile-ID */
3331 	fp = ksmbd_open_fd(work, filp);
3332 	if (IS_ERR(fp)) {
3333 		fput(filp);
3334 		rc = PTR_ERR(fp);
3335 		fp = NULL;
3336 		goto err_out;
3337 	}
3338 
3339 	/* Get Persistent-ID */
3340 	ksmbd_open_durable_fd(fp);
3341 	if (!has_file_id(fp->persistent_id)) {
3342 		rc = -ENOMEM;
3343 		goto err_out;
3344 	}
3345 
3346 	fp->cdoption = req->CreateDisposition;
3347 	fp->daccess = daccess;
3348 	fp->saccess = req->ShareAccess;
3349 	fp->coption = req->CreateOptions;
3350 
3351 	/* Set default windows and posix acls if creating new file */
3352 	if (created) {
3353 		int posix_acl_rc;
3354 		struct inode *inode = d_inode(path.dentry);
3355 
3356 		posix_acl_rc = ksmbd_vfs_inherit_posix_acl(idmap,
3357 							   &path,
3358 							   d_inode(path.dentry->d_parent));
3359 		if (posix_acl_rc)
3360 			ksmbd_debug(SMB, "inherit posix acl failed : %d\n", posix_acl_rc);
3361 
3362 		if (test_share_config_flag(work->tcon->share_conf,
3363 					   KSMBD_SHARE_FLAG_ACL_XATTR)) {
3364 			rc = smb_inherit_dacl(conn, &path, sess->user->uid,
3365 					      sess->user->gid);
3366 		}
3367 
3368 		if (rc) {
3369 			rc = smb2_create_sd_buffer(work, req, &path);
3370 			if (rc) {
3371 				if (posix_acl_rc)
3372 					ksmbd_vfs_set_init_posix_acl(idmap,
3373 								     &path);
3374 
3375 				if (test_share_config_flag(work->tcon->share_conf,
3376 							   KSMBD_SHARE_FLAG_ACL_XATTR)) {
3377 					struct smb_fattr fattr;
3378 					struct smb_ntsd *pntsd;
3379 					int pntsd_size, ace_num = 0;
3380 
3381 					ksmbd_acls_fattr(&fattr, idmap, inode);
3382 					if (fattr.cf_acls)
3383 						ace_num = fattr.cf_acls->a_count;
3384 					if (fattr.cf_dacls)
3385 						ace_num += fattr.cf_dacls->a_count;
3386 
3387 					pntsd = kmalloc(sizeof(struct smb_ntsd) +
3388 							sizeof(struct smb_sid) * 3 +
3389 							sizeof(struct smb_acl) +
3390 							sizeof(struct smb_ace) * ace_num * 2,
3391 							KSMBD_DEFAULT_GFP);
3392 					if (!pntsd) {
3393 						posix_acl_release(fattr.cf_acls);
3394 						posix_acl_release(fattr.cf_dacls);
3395 						goto err_out;
3396 					}
3397 
3398 					rc = build_sec_desc(idmap,
3399 							    pntsd, NULL, 0,
3400 							    OWNER_SECINFO |
3401 							    GROUP_SECINFO |
3402 							    DACL_SECINFO,
3403 							    &pntsd_size, &fattr);
3404 					posix_acl_release(fattr.cf_acls);
3405 					posix_acl_release(fattr.cf_dacls);
3406 					if (rc) {
3407 						kfree(pntsd);
3408 						goto err_out;
3409 					}
3410 
3411 					rc = ksmbd_vfs_set_sd_xattr(conn,
3412 								    idmap,
3413 								    &path,
3414 								    pntsd,
3415 								    pntsd_size,
3416 								    false);
3417 					kfree(pntsd);
3418 					if (rc)
3419 						pr_err("failed to store ntacl in xattr : %d\n",
3420 						       rc);
3421 				}
3422 			}
3423 		}
3424 		rc = 0;
3425 	}
3426 
3427 	if (stream_name) {
3428 		rc = smb2_set_stream_name_xattr(&path,
3429 						fp,
3430 						stream_name,
3431 						s_type);
3432 		if (rc)
3433 			goto err_out;
3434 		file_info = FILE_CREATED;
3435 	}
3436 
3437 	fp->attrib_only = !(req->DesiredAccess & ~(FILE_READ_ATTRIBUTES_LE |
3438 			FILE_WRITE_ATTRIBUTES_LE | FILE_SYNCHRONIZE_LE));
3439 
3440 	fp->is_posix_ctxt = posix_ctxt;
3441 
3442 	/* fp should be searchable through ksmbd_inode.m_fp_list
3443 	 * after daccess, saccess, attrib_only, and stream are
3444 	 * initialized.
3445 	 */
3446 	down_write(&fp->f_ci->m_lock);
3447 	list_add(&fp->node, &fp->f_ci->m_fp_list);
3448 	up_write(&fp->f_ci->m_lock);
3449 
3450 	/* Check delete pending among previous fp before oplock break */
3451 	if (ksmbd_inode_pending_delete(fp)) {
3452 		rc = -EBUSY;
3453 		goto err_out;
3454 	}
3455 
3456 	if (file_present || created)
3457 		path_put(&path);
3458 
3459 	if (!S_ISDIR(file_inode(filp)->i_mode) && open_flags & O_TRUNC &&
3460 	    !fp->attrib_only && !stream_name) {
3461 		smb_break_all_oplock(work, fp);
3462 		need_truncate = 1;
3463 	}
3464 
3465 	share_ret = ksmbd_smb_check_shared_mode(fp->filp, fp);
3466 	if (!test_share_config_flag(work->tcon->share_conf, KSMBD_SHARE_FLAG_OPLOCKS) ||
3467 	    (req_op_level == SMB2_OPLOCK_LEVEL_LEASE &&
3468 	     !(conn->vals->req_capabilities & SMB2_GLOBAL_CAP_LEASING))) {
3469 		if (share_ret < 0 && !S_ISDIR(file_inode(fp->filp)->i_mode)) {
3470 			rc = share_ret;
3471 			goto err_out1;
3472 		}
3473 	} else {
3474 		if (req_op_level == SMB2_OPLOCK_LEVEL_LEASE && lc) {
3475 			if (S_ISDIR(file_inode(filp)->i_mode)) {
3476 				lc->req_state &= ~SMB2_LEASE_WRITE_CACHING_LE;
3477 				lc->is_dir = true;
3478 			}
3479 
3480 			/*
3481 			 * Compare parent lease using parent key. If there is no
3482 			 * a lease that has same parent key, Send lease break
3483 			 * notification.
3484 			 */
3485 			smb_send_parent_lease_break_noti(fp, lc);
3486 
3487 			req_op_level = smb2_map_lease_to_oplock(lc->req_state);
3488 			ksmbd_debug(SMB,
3489 				    "lease req for(%s) req oplock state 0x%x, lease state 0x%x\n",
3490 				    name, req_op_level, lc->req_state);
3491 			rc = find_same_lease_key(sess, fp->f_ci, lc);
3492 			if (rc)
3493 				goto err_out1;
3494 		} else if (open_flags == O_RDONLY &&
3495 			   (req_op_level == SMB2_OPLOCK_LEVEL_BATCH ||
3496 			    req_op_level == SMB2_OPLOCK_LEVEL_EXCLUSIVE))
3497 			req_op_level = SMB2_OPLOCK_LEVEL_II;
3498 
3499 		rc = smb_grant_oplock(work, req_op_level,
3500 				      fp->persistent_id, fp,
3501 				      le32_to_cpu(req->hdr.Id.SyncId.TreeId),
3502 				      lc, share_ret);
3503 		if (rc < 0)
3504 			goto err_out1;
3505 	}
3506 
3507 	if (req->CreateOptions & FILE_DELETE_ON_CLOSE_LE)
3508 		ksmbd_fd_set_delete_on_close(fp, file_info);
3509 
3510 	if (need_truncate) {
3511 		rc = smb2_create_truncate(&fp->filp->f_path);
3512 		if (rc)
3513 			goto err_out1;
3514 	}
3515 
3516 	if (req->CreateContextsOffset) {
3517 		struct create_alloc_size_req *az_req;
3518 
3519 		az_req = (struct create_alloc_size_req *)smb2_find_context_vals(req,
3520 					SMB2_CREATE_ALLOCATION_SIZE, 4);
3521 		if (IS_ERR(az_req)) {
3522 			rc = PTR_ERR(az_req);
3523 			goto err_out1;
3524 		} else if (az_req) {
3525 			loff_t alloc_size;
3526 			int err;
3527 
3528 			if (le16_to_cpu(az_req->ccontext.DataOffset) +
3529 			    le32_to_cpu(az_req->ccontext.DataLength) <
3530 			    sizeof(struct create_alloc_size_req)) {
3531 				rc = -EINVAL;
3532 				goto err_out1;
3533 			}
3534 			alloc_size = le64_to_cpu(az_req->AllocationSize);
3535 			ksmbd_debug(SMB,
3536 				    "request smb2 create allocate size : %llu\n",
3537 				    alloc_size);
3538 			smb_break_all_levII_oplock(work, fp, 1);
3539 			err = vfs_fallocate(fp->filp, FALLOC_FL_KEEP_SIZE, 0,
3540 					    alloc_size);
3541 			if (err < 0)
3542 				ksmbd_debug(SMB,
3543 					    "vfs_fallocate is failed : %d\n",
3544 					    err);
3545 		}
3546 
3547 		context = smb2_find_context_vals(req, SMB2_CREATE_QUERY_ON_DISK_ID, 4);
3548 		if (IS_ERR(context)) {
3549 			rc = PTR_ERR(context);
3550 			goto err_out1;
3551 		} else if (context) {
3552 			ksmbd_debug(SMB, "get query on disk id context\n");
3553 			query_disk_id = 1;
3554 		}
3555 
3556 		if (conn->is_aapl == false) {
3557 			context = smb2_find_context_vals(req, SMB2_CREATE_AAPL, 4);
3558 			if (IS_ERR(context)) {
3559 				rc = PTR_ERR(context);
3560 				goto err_out1;
3561 			} else if (context)
3562 				conn->is_aapl = true;
3563 		}
3564 	}
3565 
3566 	rc = ksmbd_vfs_getattr(&path, &stat);
3567 	if (rc)
3568 		goto err_out1;
3569 
3570 	if (stat.result_mask & STATX_BTIME)
3571 		fp->create_time = ksmbd_UnixTimeToNT(stat.btime);
3572 	else
3573 		fp->create_time = ksmbd_UnixTimeToNT(stat.ctime);
3574 	if (req->FileAttributes || fp->f_ci->m_fattr == 0)
3575 		fp->f_ci->m_fattr =
3576 			cpu_to_le32(smb2_get_dos_mode(&stat, le32_to_cpu(req->FileAttributes)));
3577 
3578 	if (!created)
3579 		smb2_update_xattrs(tcon, &path, fp);
3580 	else
3581 		smb2_new_xattrs(tcon, &path, fp);
3582 
3583 	memcpy(fp->client_guid, conn->ClientGUID, SMB2_CLIENT_GUID_SIZE);
3584 
3585 	if (dh_info.type == DURABLE_REQ_V2 || dh_info.type == DURABLE_REQ) {
3586 		if (dh_info.type == DURABLE_REQ_V2 && dh_info.persistent &&
3587 		    test_share_config_flag(work->tcon->share_conf,
3588 					   KSMBD_SHARE_FLAG_CONTINUOUS_AVAILABILITY))
3589 			fp->is_persistent = true;
3590 		else
3591 			fp->is_durable = true;
3592 
3593 		if (dh_info.type == DURABLE_REQ_V2) {
3594 			memcpy(fp->create_guid, dh_info.CreateGuid,
3595 					SMB2_CREATE_GUID_SIZE);
3596 			if (dh_info.timeout)
3597 				fp->durable_timeout =
3598 					min_t(unsigned int, dh_info.timeout,
3599 					      DURABLE_HANDLE_MAX_TIMEOUT);
3600 			else
3601 				fp->durable_timeout = 60;
3602 		}
3603 	}
3604 
3605 reconnected_fp:
3606 	rsp->StructureSize = cpu_to_le16(89);
3607 	rcu_read_lock();
3608 	opinfo = rcu_dereference(fp->f_opinfo);
3609 	rsp->OplockLevel = opinfo != NULL ? opinfo->level : 0;
3610 	rcu_read_unlock();
3611 	rsp->Flags = 0;
3612 	rsp->CreateAction = cpu_to_le32(file_info);
3613 	rsp->CreationTime = cpu_to_le64(fp->create_time);
3614 	time = ksmbd_UnixTimeToNT(stat.atime);
3615 	rsp->LastAccessTime = cpu_to_le64(time);
3616 	time = ksmbd_UnixTimeToNT(stat.mtime);
3617 	rsp->LastWriteTime = cpu_to_le64(time);
3618 	time = ksmbd_UnixTimeToNT(stat.ctime);
3619 	rsp->ChangeTime = cpu_to_le64(time);
3620 	rsp->AllocationSize = S_ISDIR(stat.mode) ? 0 :
3621 		cpu_to_le64(stat.blocks << 9);
3622 	rsp->EndofFile = S_ISDIR(stat.mode) ? 0 : cpu_to_le64(stat.size);
3623 	rsp->FileAttributes = fp->f_ci->m_fattr;
3624 
3625 	rsp->Reserved2 = 0;
3626 
3627 	rsp->PersistentFileId = fp->persistent_id;
3628 	rsp->VolatileFileId = fp->volatile_id;
3629 
3630 	rsp->CreateContextsOffset = 0;
3631 	rsp->CreateContextsLength = 0;
3632 	iov_len = offsetof(struct smb2_create_rsp, Buffer);
3633 
3634 	/* If lease is request send lease context response */
3635 	if (opinfo && opinfo->is_lease) {
3636 		struct create_context *lease_ccontext;
3637 
3638 		ksmbd_debug(SMB, "lease granted on(%s) lease state 0x%x\n",
3639 			    name, opinfo->o_lease->state);
3640 		rsp->OplockLevel = SMB2_OPLOCK_LEVEL_LEASE;
3641 
3642 		lease_ccontext = (struct create_context *)rsp->Buffer;
3643 		contxt_cnt++;
3644 		create_lease_buf(rsp->Buffer, opinfo->o_lease);
3645 		le32_add_cpu(&rsp->CreateContextsLength,
3646 			     conn->vals->create_lease_size);
3647 		iov_len += conn->vals->create_lease_size;
3648 		next_ptr = &lease_ccontext->Next;
3649 		next_off = conn->vals->create_lease_size;
3650 	}
3651 
3652 	if (maximal_access_ctxt) {
3653 		struct create_context *mxac_ccontext;
3654 
3655 		if (maximal_access == 0)
3656 			ksmbd_vfs_query_maximal_access(idmap,
3657 						       path.dentry,
3658 						       &maximal_access);
3659 		mxac_ccontext = (struct create_context *)(rsp->Buffer +
3660 				le32_to_cpu(rsp->CreateContextsLength));
3661 		contxt_cnt++;
3662 		create_mxac_rsp_buf(rsp->Buffer +
3663 				le32_to_cpu(rsp->CreateContextsLength),
3664 				le32_to_cpu(maximal_access));
3665 		le32_add_cpu(&rsp->CreateContextsLength,
3666 			     conn->vals->create_mxac_size);
3667 		iov_len += conn->vals->create_mxac_size;
3668 		if (next_ptr)
3669 			*next_ptr = cpu_to_le32(next_off);
3670 		next_ptr = &mxac_ccontext->Next;
3671 		next_off = conn->vals->create_mxac_size;
3672 	}
3673 
3674 	if (query_disk_id) {
3675 		struct create_context *disk_id_ccontext;
3676 
3677 		disk_id_ccontext = (struct create_context *)(rsp->Buffer +
3678 				le32_to_cpu(rsp->CreateContextsLength));
3679 		contxt_cnt++;
3680 		create_disk_id_rsp_buf(rsp->Buffer +
3681 				le32_to_cpu(rsp->CreateContextsLength),
3682 				stat.ino, tcon->id);
3683 		le32_add_cpu(&rsp->CreateContextsLength,
3684 			     conn->vals->create_disk_id_size);
3685 		iov_len += conn->vals->create_disk_id_size;
3686 		if (next_ptr)
3687 			*next_ptr = cpu_to_le32(next_off);
3688 		next_ptr = &disk_id_ccontext->Next;
3689 		next_off = conn->vals->create_disk_id_size;
3690 	}
3691 
3692 	if (dh_info.type == DURABLE_REQ || dh_info.type == DURABLE_REQ_V2) {
3693 		struct create_context *durable_ccontext;
3694 
3695 		durable_ccontext = (struct create_context *)(rsp->Buffer +
3696 				le32_to_cpu(rsp->CreateContextsLength));
3697 		contxt_cnt++;
3698 		if (dh_info.type == DURABLE_REQ) {
3699 			create_durable_rsp_buf(rsp->Buffer +
3700 					le32_to_cpu(rsp->CreateContextsLength));
3701 			le32_add_cpu(&rsp->CreateContextsLength,
3702 					conn->vals->create_durable_size);
3703 			iov_len += conn->vals->create_durable_size;
3704 		} else {
3705 			create_durable_v2_rsp_buf(rsp->Buffer +
3706 					le32_to_cpu(rsp->CreateContextsLength),
3707 					fp);
3708 			le32_add_cpu(&rsp->CreateContextsLength,
3709 					conn->vals->create_durable_v2_size);
3710 			iov_len += conn->vals->create_durable_v2_size;
3711 		}
3712 
3713 		if (next_ptr)
3714 			*next_ptr = cpu_to_le32(next_off);
3715 		next_ptr = &durable_ccontext->Next;
3716 		next_off = conn->vals->create_durable_size;
3717 	}
3718 
3719 	if (posix_ctxt) {
3720 		contxt_cnt++;
3721 		create_posix_rsp_buf(rsp->Buffer +
3722 				le32_to_cpu(rsp->CreateContextsLength),
3723 				fp);
3724 		le32_add_cpu(&rsp->CreateContextsLength,
3725 			     conn->vals->create_posix_size);
3726 		iov_len += conn->vals->create_posix_size;
3727 		if (next_ptr)
3728 			*next_ptr = cpu_to_le32(next_off);
3729 	}
3730 
3731 	if (contxt_cnt > 0) {
3732 		rsp->CreateContextsOffset =
3733 			cpu_to_le32(offsetof(struct smb2_create_rsp, Buffer));
3734 	}
3735 
3736 err_out:
3737 	if (rc && (file_present || created))
3738 		path_put(&path);
3739 
3740 err_out1:
3741 	ksmbd_revert_fsids(work);
3742 
3743 err_out2:
3744 	if (!rc) {
3745 		ksmbd_update_fstate(&work->sess->file_table, fp, FP_INITED);
3746 		rc = ksmbd_iov_pin_rsp(work, (void *)rsp, iov_len);
3747 	}
3748 	if (rc) {
3749 		if (rc == -EINVAL)
3750 			rsp->hdr.Status = STATUS_INVALID_PARAMETER;
3751 		else if (rc == -EOPNOTSUPP)
3752 			rsp->hdr.Status = STATUS_NOT_SUPPORTED;
3753 		else if (rc == -EACCES || rc == -ESTALE || rc == -EXDEV)
3754 			rsp->hdr.Status = STATUS_ACCESS_DENIED;
3755 		else if (rc == -ENOENT)
3756 			rsp->hdr.Status = STATUS_OBJECT_NAME_INVALID;
3757 		else if (rc == -EPERM)
3758 			rsp->hdr.Status = STATUS_SHARING_VIOLATION;
3759 		else if (rc == -EBUSY)
3760 			rsp->hdr.Status = STATUS_DELETE_PENDING;
3761 		else if (rc == -EBADF)
3762 			rsp->hdr.Status = STATUS_OBJECT_NAME_NOT_FOUND;
3763 		else if (rc == -ENOEXEC)
3764 			rsp->hdr.Status = STATUS_DUPLICATE_OBJECTID;
3765 		else if (rc == -ENXIO)
3766 			rsp->hdr.Status = STATUS_NO_SUCH_DEVICE;
3767 		else if (rc == -EEXIST)
3768 			rsp->hdr.Status = STATUS_OBJECT_NAME_COLLISION;
3769 		else if (rc == -EMFILE)
3770 			rsp->hdr.Status = STATUS_INSUFFICIENT_RESOURCES;
3771 		if (!rsp->hdr.Status)
3772 			rsp->hdr.Status = STATUS_UNEXPECTED_IO_ERROR;
3773 
3774 		if (fp)
3775 			ksmbd_fd_put(work, fp);
3776 		smb2_set_err_rsp(work);
3777 		ksmbd_debug(SMB, "Error response: %x\n", rsp->hdr.Status);
3778 	}
3779 
3780 	kfree(name);
3781 	kfree(lc);
3782 
3783 	return rc;
3784 }
3785 
3786 static int readdir_info_level_struct_sz(int info_level)
3787 {
3788 	switch (info_level) {
3789 	case FILE_FULL_DIRECTORY_INFORMATION:
3790 		return sizeof(FILE_FULL_DIRECTORY_INFO);
3791 	case FILE_BOTH_DIRECTORY_INFORMATION:
3792 		return sizeof(FILE_BOTH_DIRECTORY_INFO);
3793 	case FILE_DIRECTORY_INFORMATION:
3794 		return sizeof(FILE_DIRECTORY_INFO);
3795 	case FILE_NAMES_INFORMATION:
3796 		return sizeof(struct file_names_info);
3797 	case FILEID_FULL_DIRECTORY_INFORMATION:
3798 		return sizeof(FILE_ID_FULL_DIR_INFO);
3799 	case FILEID_BOTH_DIRECTORY_INFORMATION:
3800 		return sizeof(struct file_id_both_directory_info);
3801 	case SMB_FIND_FILE_POSIX_INFO:
3802 		return sizeof(struct smb2_posix_info);
3803 	default:
3804 		return -EOPNOTSUPP;
3805 	}
3806 }
3807 
3808 static int dentry_name(struct ksmbd_dir_info *d_info, int info_level)
3809 {
3810 	switch (info_level) {
3811 	case FILE_FULL_DIRECTORY_INFORMATION:
3812 	{
3813 		FILE_FULL_DIRECTORY_INFO *ffdinfo;
3814 
3815 		ffdinfo = (FILE_FULL_DIRECTORY_INFO *)d_info->rptr;
3816 		d_info->rptr += le32_to_cpu(ffdinfo->NextEntryOffset);
3817 		d_info->name = ffdinfo->FileName;
3818 		d_info->name_len = le32_to_cpu(ffdinfo->FileNameLength);
3819 		return 0;
3820 	}
3821 	case FILE_BOTH_DIRECTORY_INFORMATION:
3822 	{
3823 		FILE_BOTH_DIRECTORY_INFO *fbdinfo;
3824 
3825 		fbdinfo = (FILE_BOTH_DIRECTORY_INFO *)d_info->rptr;
3826 		d_info->rptr += le32_to_cpu(fbdinfo->NextEntryOffset);
3827 		d_info->name = fbdinfo->FileName;
3828 		d_info->name_len = le32_to_cpu(fbdinfo->FileNameLength);
3829 		return 0;
3830 	}
3831 	case FILE_DIRECTORY_INFORMATION:
3832 	{
3833 		FILE_DIRECTORY_INFO *fdinfo;
3834 
3835 		fdinfo = (FILE_DIRECTORY_INFO *)d_info->rptr;
3836 		d_info->rptr += le32_to_cpu(fdinfo->NextEntryOffset);
3837 		d_info->name = fdinfo->FileName;
3838 		d_info->name_len = le32_to_cpu(fdinfo->FileNameLength);
3839 		return 0;
3840 	}
3841 	case FILE_NAMES_INFORMATION:
3842 	{
3843 		struct file_names_info *fninfo;
3844 
3845 		fninfo = (struct file_names_info *)d_info->rptr;
3846 		d_info->rptr += le32_to_cpu(fninfo->NextEntryOffset);
3847 		d_info->name = fninfo->FileName;
3848 		d_info->name_len = le32_to_cpu(fninfo->FileNameLength);
3849 		return 0;
3850 	}
3851 	case FILEID_FULL_DIRECTORY_INFORMATION:
3852 	{
3853 		FILE_ID_FULL_DIR_INFO *dinfo;
3854 
3855 		dinfo = (FILE_ID_FULL_DIR_INFO *)d_info->rptr;
3856 		d_info->rptr += le32_to_cpu(dinfo->NextEntryOffset);
3857 		d_info->name = dinfo->FileName;
3858 		d_info->name_len = le32_to_cpu(dinfo->FileNameLength);
3859 		return 0;
3860 	}
3861 	case FILEID_BOTH_DIRECTORY_INFORMATION:
3862 	{
3863 		struct file_id_both_directory_info *fibdinfo;
3864 
3865 		fibdinfo = (struct file_id_both_directory_info *)d_info->rptr;
3866 		d_info->rptr += le32_to_cpu(fibdinfo->NextEntryOffset);
3867 		d_info->name = fibdinfo->FileName;
3868 		d_info->name_len = le32_to_cpu(fibdinfo->FileNameLength);
3869 		return 0;
3870 	}
3871 	case SMB_FIND_FILE_POSIX_INFO:
3872 	{
3873 		struct smb2_posix_info *posix_info;
3874 
3875 		posix_info = (struct smb2_posix_info *)d_info->rptr;
3876 		d_info->rptr += le32_to_cpu(posix_info->NextEntryOffset);
3877 		d_info->name = posix_info->name;
3878 		d_info->name_len = le32_to_cpu(posix_info->name_len);
3879 		return 0;
3880 	}
3881 	default:
3882 		return -EINVAL;
3883 	}
3884 }
3885 
3886 /**
3887  * smb2_populate_readdir_entry() - encode directory entry in smb2 response
3888  * buffer
3889  * @conn:	connection instance
3890  * @info_level:	smb information level
3891  * @d_info:	structure included variables for query dir
3892  * @ksmbd_kstat:	ksmbd wrapper of dirent stat information
3893  *
3894  * if directory has many entries, find first can't read it fully.
3895  * find next might be called multiple times to read remaining dir entries
3896  *
3897  * Return:	0 on success, otherwise error
3898  */
3899 static int smb2_populate_readdir_entry(struct ksmbd_conn *conn, int info_level,
3900 				       struct ksmbd_dir_info *d_info,
3901 				       struct ksmbd_kstat *ksmbd_kstat)
3902 {
3903 	int next_entry_offset = 0;
3904 	char *conv_name;
3905 	int conv_len;
3906 	void *kstat;
3907 	int struct_sz, rc = 0;
3908 
3909 	conv_name = ksmbd_convert_dir_info_name(d_info,
3910 						conn->local_nls,
3911 						&conv_len);
3912 	if (!conv_name)
3913 		return -ENOMEM;
3914 
3915 	/* Somehow the name has only terminating NULL bytes */
3916 	if (conv_len < 0) {
3917 		rc = -EINVAL;
3918 		goto free_conv_name;
3919 	}
3920 
3921 	struct_sz = readdir_info_level_struct_sz(info_level) + conv_len;
3922 	next_entry_offset = ALIGN(struct_sz, KSMBD_DIR_INFO_ALIGNMENT);
3923 	d_info->last_entry_off_align = next_entry_offset - struct_sz;
3924 
3925 	if (next_entry_offset > d_info->out_buf_len) {
3926 		d_info->out_buf_len = 0;
3927 		rc = -ENOSPC;
3928 		goto free_conv_name;
3929 	}
3930 
3931 	kstat = d_info->wptr;
3932 	if (info_level != FILE_NAMES_INFORMATION)
3933 		kstat = ksmbd_vfs_init_kstat(&d_info->wptr, ksmbd_kstat);
3934 
3935 	switch (info_level) {
3936 	case FILE_FULL_DIRECTORY_INFORMATION:
3937 	{
3938 		FILE_FULL_DIRECTORY_INFO *ffdinfo;
3939 
3940 		ffdinfo = (FILE_FULL_DIRECTORY_INFO *)kstat;
3941 		ffdinfo->FileNameLength = cpu_to_le32(conv_len);
3942 		ffdinfo->EaSize =
3943 			smb2_get_reparse_tag_special_file(ksmbd_kstat->kstat->mode);
3944 		if (ffdinfo->EaSize)
3945 			ffdinfo->ExtFileAttributes = FILE_ATTRIBUTE_REPARSE_POINT_LE;
3946 		if (d_info->hide_dot_file && d_info->name[0] == '.')
3947 			ffdinfo->ExtFileAttributes |= FILE_ATTRIBUTE_HIDDEN_LE;
3948 		memcpy(ffdinfo->FileName, conv_name, conv_len);
3949 		ffdinfo->NextEntryOffset = cpu_to_le32(next_entry_offset);
3950 		break;
3951 	}
3952 	case FILE_BOTH_DIRECTORY_INFORMATION:
3953 	{
3954 		FILE_BOTH_DIRECTORY_INFO *fbdinfo;
3955 
3956 		fbdinfo = (FILE_BOTH_DIRECTORY_INFO *)kstat;
3957 		fbdinfo->FileNameLength = cpu_to_le32(conv_len);
3958 		fbdinfo->EaSize =
3959 			smb2_get_reparse_tag_special_file(ksmbd_kstat->kstat->mode);
3960 		if (fbdinfo->EaSize)
3961 			fbdinfo->ExtFileAttributes = FILE_ATTRIBUTE_REPARSE_POINT_LE;
3962 		fbdinfo->ShortNameLength = 0;
3963 		fbdinfo->Reserved = 0;
3964 		if (d_info->hide_dot_file && d_info->name[0] == '.')
3965 			fbdinfo->ExtFileAttributes |= FILE_ATTRIBUTE_HIDDEN_LE;
3966 		memcpy(fbdinfo->FileName, conv_name, conv_len);
3967 		fbdinfo->NextEntryOffset = cpu_to_le32(next_entry_offset);
3968 		break;
3969 	}
3970 	case FILE_DIRECTORY_INFORMATION:
3971 	{
3972 		FILE_DIRECTORY_INFO *fdinfo;
3973 
3974 		fdinfo = (FILE_DIRECTORY_INFO *)kstat;
3975 		fdinfo->FileNameLength = cpu_to_le32(conv_len);
3976 		if (d_info->hide_dot_file && d_info->name[0] == '.')
3977 			fdinfo->ExtFileAttributes |= FILE_ATTRIBUTE_HIDDEN_LE;
3978 		memcpy(fdinfo->FileName, conv_name, conv_len);
3979 		fdinfo->NextEntryOffset = cpu_to_le32(next_entry_offset);
3980 		break;
3981 	}
3982 	case FILE_NAMES_INFORMATION:
3983 	{
3984 		struct file_names_info *fninfo;
3985 
3986 		fninfo = (struct file_names_info *)kstat;
3987 		fninfo->FileNameLength = cpu_to_le32(conv_len);
3988 		memcpy(fninfo->FileName, conv_name, conv_len);
3989 		fninfo->NextEntryOffset = cpu_to_le32(next_entry_offset);
3990 		break;
3991 	}
3992 	case FILEID_FULL_DIRECTORY_INFORMATION:
3993 	{
3994 		FILE_ID_FULL_DIR_INFO *dinfo;
3995 
3996 		dinfo = (FILE_ID_FULL_DIR_INFO *)kstat;
3997 		dinfo->FileNameLength = cpu_to_le32(conv_len);
3998 		dinfo->EaSize =
3999 			smb2_get_reparse_tag_special_file(ksmbd_kstat->kstat->mode);
4000 		if (dinfo->EaSize)
4001 			dinfo->ExtFileAttributes = FILE_ATTRIBUTE_REPARSE_POINT_LE;
4002 		dinfo->Reserved = 0;
4003 		if (conn->is_aapl)
4004 			dinfo->UniqueId = 0;
4005 		else
4006 			dinfo->UniqueId = cpu_to_le64(ksmbd_kstat->kstat->ino);
4007 		if (d_info->hide_dot_file && d_info->name[0] == '.')
4008 			dinfo->ExtFileAttributes |= FILE_ATTRIBUTE_HIDDEN_LE;
4009 		memcpy(dinfo->FileName, conv_name, conv_len);
4010 		dinfo->NextEntryOffset = cpu_to_le32(next_entry_offset);
4011 		break;
4012 	}
4013 	case FILEID_BOTH_DIRECTORY_INFORMATION:
4014 	{
4015 		struct file_id_both_directory_info *fibdinfo;
4016 
4017 		fibdinfo = (struct file_id_both_directory_info *)kstat;
4018 		fibdinfo->FileNameLength = cpu_to_le32(conv_len);
4019 		fibdinfo->EaSize =
4020 			smb2_get_reparse_tag_special_file(ksmbd_kstat->kstat->mode);
4021 		if (fibdinfo->EaSize)
4022 			fibdinfo->ExtFileAttributes = FILE_ATTRIBUTE_REPARSE_POINT_LE;
4023 		if (conn->is_aapl)
4024 			fibdinfo->UniqueId = 0;
4025 		else
4026 			fibdinfo->UniqueId = cpu_to_le64(ksmbd_kstat->kstat->ino);
4027 		fibdinfo->ShortNameLength = 0;
4028 		fibdinfo->Reserved = 0;
4029 		fibdinfo->Reserved2 = cpu_to_le16(0);
4030 		if (d_info->hide_dot_file && d_info->name[0] == '.')
4031 			fibdinfo->ExtFileAttributes |= FILE_ATTRIBUTE_HIDDEN_LE;
4032 		memcpy(fibdinfo->FileName, conv_name, conv_len);
4033 		fibdinfo->NextEntryOffset = cpu_to_le32(next_entry_offset);
4034 		break;
4035 	}
4036 	case SMB_FIND_FILE_POSIX_INFO:
4037 	{
4038 		struct smb2_posix_info *posix_info;
4039 		u64 time;
4040 
4041 		posix_info = (struct smb2_posix_info *)kstat;
4042 		posix_info->Ignored = 0;
4043 		posix_info->CreationTime = cpu_to_le64(ksmbd_kstat->create_time);
4044 		time = ksmbd_UnixTimeToNT(ksmbd_kstat->kstat->ctime);
4045 		posix_info->ChangeTime = cpu_to_le64(time);
4046 		time = ksmbd_UnixTimeToNT(ksmbd_kstat->kstat->atime);
4047 		posix_info->LastAccessTime = cpu_to_le64(time);
4048 		time = ksmbd_UnixTimeToNT(ksmbd_kstat->kstat->mtime);
4049 		posix_info->LastWriteTime = cpu_to_le64(time);
4050 		posix_info->EndOfFile = cpu_to_le64(ksmbd_kstat->kstat->size);
4051 		posix_info->AllocationSize = cpu_to_le64(ksmbd_kstat->kstat->blocks << 9);
4052 		posix_info->DeviceId = cpu_to_le32(ksmbd_kstat->kstat->rdev);
4053 		posix_info->HardLinks = cpu_to_le32(ksmbd_kstat->kstat->nlink);
4054 		posix_info->Mode = cpu_to_le32(ksmbd_kstat->kstat->mode & 0777);
4055 		switch (ksmbd_kstat->kstat->mode & S_IFMT) {
4056 		case S_IFDIR:
4057 			posix_info->Mode |= cpu_to_le32(POSIX_TYPE_DIR << POSIX_FILETYPE_SHIFT);
4058 			break;
4059 		case S_IFLNK:
4060 			posix_info->Mode |= cpu_to_le32(POSIX_TYPE_SYMLINK << POSIX_FILETYPE_SHIFT);
4061 			break;
4062 		case S_IFCHR:
4063 			posix_info->Mode |= cpu_to_le32(POSIX_TYPE_CHARDEV << POSIX_FILETYPE_SHIFT);
4064 			break;
4065 		case S_IFBLK:
4066 			posix_info->Mode |= cpu_to_le32(POSIX_TYPE_BLKDEV << POSIX_FILETYPE_SHIFT);
4067 			break;
4068 		case S_IFIFO:
4069 			posix_info->Mode |= cpu_to_le32(POSIX_TYPE_FIFO << POSIX_FILETYPE_SHIFT);
4070 			break;
4071 		case S_IFSOCK:
4072 			posix_info->Mode |= cpu_to_le32(POSIX_TYPE_SOCKET << POSIX_FILETYPE_SHIFT);
4073 		}
4074 
4075 		posix_info->Inode = cpu_to_le64(ksmbd_kstat->kstat->ino);
4076 		posix_info->DosAttributes =
4077 			S_ISDIR(ksmbd_kstat->kstat->mode) ?
4078 				FILE_ATTRIBUTE_DIRECTORY_LE : FILE_ATTRIBUTE_ARCHIVE_LE;
4079 		if (d_info->hide_dot_file && d_info->name[0] == '.')
4080 			posix_info->DosAttributes |= FILE_ATTRIBUTE_HIDDEN_LE;
4081 		/*
4082 		 * SidBuffer(32) contain two sids(Domain sid(16), UNIX group sid(16)).
4083 		 * UNIX sid(16) = revision(1) + num_subauth(1) + authority(6) +
4084 		 *		  sub_auth(4 * 1(num_subauth)) + RID(4).
4085 		 */
4086 		id_to_sid(from_kuid_munged(&init_user_ns, ksmbd_kstat->kstat->uid),
4087 			  SIDUNIX_USER, (struct smb_sid *)&posix_info->SidBuffer[0]);
4088 		id_to_sid(from_kgid_munged(&init_user_ns, ksmbd_kstat->kstat->gid),
4089 			  SIDUNIX_GROUP, (struct smb_sid *)&posix_info->SidBuffer[16]);
4090 		memcpy(posix_info->name, conv_name, conv_len);
4091 		posix_info->name_len = cpu_to_le32(conv_len);
4092 		posix_info->NextEntryOffset = cpu_to_le32(next_entry_offset);
4093 		break;
4094 	}
4095 
4096 	} /* switch (info_level) */
4097 
4098 	d_info->last_entry_offset = d_info->data_count;
4099 	d_info->data_count += next_entry_offset;
4100 	d_info->out_buf_len -= next_entry_offset;
4101 	d_info->wptr += next_entry_offset;
4102 
4103 	ksmbd_debug(SMB,
4104 		    "info_level : %d, buf_len :%d, next_offset : %d, data_count : %d\n",
4105 		    info_level, d_info->out_buf_len,
4106 		    next_entry_offset, d_info->data_count);
4107 
4108 free_conv_name:
4109 	kfree(conv_name);
4110 	return rc;
4111 }
4112 
4113 struct smb2_query_dir_private {
4114 	struct ksmbd_work	*work;
4115 	char			*search_pattern;
4116 	struct ksmbd_file	*dir_fp;
4117 
4118 	struct ksmbd_dir_info	*d_info;
4119 	int			info_level;
4120 };
4121 
4122 static int process_query_dir_entries(struct smb2_query_dir_private *priv)
4123 {
4124 	struct mnt_idmap	*idmap = file_mnt_idmap(priv->dir_fp->filp);
4125 	struct kstat		kstat;
4126 	struct ksmbd_kstat	ksmbd_kstat;
4127 	int			rc;
4128 	int			i;
4129 
4130 	for (i = 0; i < priv->d_info->num_entry; i++) {
4131 		struct dentry *dent;
4132 
4133 		if (dentry_name(priv->d_info, priv->info_level))
4134 			return -EINVAL;
4135 
4136 		dent = lookup_one_unlocked(idmap,
4137 					   &QSTR_LEN(priv->d_info->name,
4138 						     priv->d_info->name_len),
4139 					   priv->dir_fp->filp->f_path.dentry);
4140 
4141 		if (IS_ERR(dent)) {
4142 			ksmbd_debug(SMB, "Cannot lookup `%s' [%ld]\n",
4143 				    priv->d_info->name,
4144 				    PTR_ERR(dent));
4145 			continue;
4146 		}
4147 		if (unlikely(d_is_negative(dent))) {
4148 			dput(dent);
4149 			ksmbd_debug(SMB, "Negative dentry `%s'\n",
4150 				    priv->d_info->name);
4151 			continue;
4152 		}
4153 
4154 		ksmbd_kstat.kstat = &kstat;
4155 		if (priv->info_level != FILE_NAMES_INFORMATION) {
4156 			rc = ksmbd_vfs_fill_dentry_attrs(priv->work,
4157 							 idmap,
4158 							 dent,
4159 							 &ksmbd_kstat);
4160 			if (rc) {
4161 				dput(dent);
4162 				continue;
4163 			}
4164 		}
4165 
4166 		rc = smb2_populate_readdir_entry(priv->work->conn,
4167 						 priv->info_level,
4168 						 priv->d_info,
4169 						 &ksmbd_kstat);
4170 		dput(dent);
4171 		if (rc)
4172 			return rc;
4173 	}
4174 	return 0;
4175 }
4176 
4177 static int reserve_populate_dentry(struct ksmbd_dir_info *d_info,
4178 				   int info_level)
4179 {
4180 	int struct_sz;
4181 	int conv_len;
4182 	int next_entry_offset;
4183 
4184 	struct_sz = readdir_info_level_struct_sz(info_level);
4185 	if (struct_sz == -EOPNOTSUPP)
4186 		return -EOPNOTSUPP;
4187 
4188 	conv_len = (d_info->name_len + 1) * 2;
4189 	next_entry_offset = ALIGN(struct_sz + conv_len,
4190 				  KSMBD_DIR_INFO_ALIGNMENT);
4191 
4192 	if (next_entry_offset > d_info->out_buf_len) {
4193 		d_info->out_buf_len = 0;
4194 		return -ENOSPC;
4195 	}
4196 
4197 	switch (info_level) {
4198 	case FILE_FULL_DIRECTORY_INFORMATION:
4199 	{
4200 		FILE_FULL_DIRECTORY_INFO *ffdinfo;
4201 
4202 		ffdinfo = (FILE_FULL_DIRECTORY_INFO *)d_info->wptr;
4203 		memcpy(ffdinfo->FileName, d_info->name, d_info->name_len);
4204 		ffdinfo->FileName[d_info->name_len] = 0x00;
4205 		ffdinfo->FileNameLength = cpu_to_le32(d_info->name_len);
4206 		ffdinfo->NextEntryOffset = cpu_to_le32(next_entry_offset);
4207 		break;
4208 	}
4209 	case FILE_BOTH_DIRECTORY_INFORMATION:
4210 	{
4211 		FILE_BOTH_DIRECTORY_INFO *fbdinfo;
4212 
4213 		fbdinfo = (FILE_BOTH_DIRECTORY_INFO *)d_info->wptr;
4214 		memcpy(fbdinfo->FileName, d_info->name, d_info->name_len);
4215 		fbdinfo->FileName[d_info->name_len] = 0x00;
4216 		fbdinfo->FileNameLength = cpu_to_le32(d_info->name_len);
4217 		fbdinfo->NextEntryOffset = cpu_to_le32(next_entry_offset);
4218 		break;
4219 	}
4220 	case FILE_DIRECTORY_INFORMATION:
4221 	{
4222 		FILE_DIRECTORY_INFO *fdinfo;
4223 
4224 		fdinfo = (FILE_DIRECTORY_INFO *)d_info->wptr;
4225 		memcpy(fdinfo->FileName, d_info->name, d_info->name_len);
4226 		fdinfo->FileName[d_info->name_len] = 0x00;
4227 		fdinfo->FileNameLength = cpu_to_le32(d_info->name_len);
4228 		fdinfo->NextEntryOffset = cpu_to_le32(next_entry_offset);
4229 		break;
4230 	}
4231 	case FILE_NAMES_INFORMATION:
4232 	{
4233 		struct file_names_info *fninfo;
4234 
4235 		fninfo = (struct file_names_info *)d_info->wptr;
4236 		memcpy(fninfo->FileName, d_info->name, d_info->name_len);
4237 		fninfo->FileName[d_info->name_len] = 0x00;
4238 		fninfo->FileNameLength = cpu_to_le32(d_info->name_len);
4239 		fninfo->NextEntryOffset = cpu_to_le32(next_entry_offset);
4240 		break;
4241 	}
4242 	case FILEID_FULL_DIRECTORY_INFORMATION:
4243 	{
4244 		FILE_ID_FULL_DIR_INFO *dinfo;
4245 
4246 		dinfo = (FILE_ID_FULL_DIR_INFO *)d_info->wptr;
4247 		memcpy(dinfo->FileName, d_info->name, d_info->name_len);
4248 		dinfo->FileName[d_info->name_len] = 0x00;
4249 		dinfo->FileNameLength = cpu_to_le32(d_info->name_len);
4250 		dinfo->NextEntryOffset = cpu_to_le32(next_entry_offset);
4251 		break;
4252 	}
4253 	case FILEID_BOTH_DIRECTORY_INFORMATION:
4254 	{
4255 		struct file_id_both_directory_info *fibdinfo;
4256 
4257 		fibdinfo = (struct file_id_both_directory_info *)d_info->wptr;
4258 		memcpy(fibdinfo->FileName, d_info->name, d_info->name_len);
4259 		fibdinfo->FileName[d_info->name_len] = 0x00;
4260 		fibdinfo->FileNameLength = cpu_to_le32(d_info->name_len);
4261 		fibdinfo->NextEntryOffset = cpu_to_le32(next_entry_offset);
4262 		break;
4263 	}
4264 	case SMB_FIND_FILE_POSIX_INFO:
4265 	{
4266 		struct smb2_posix_info *posix_info;
4267 
4268 		posix_info = (struct smb2_posix_info *)d_info->wptr;
4269 		memcpy(posix_info->name, d_info->name, d_info->name_len);
4270 		posix_info->name[d_info->name_len] = 0x00;
4271 		posix_info->name_len = cpu_to_le32(d_info->name_len);
4272 		posix_info->NextEntryOffset =
4273 			cpu_to_le32(next_entry_offset);
4274 		break;
4275 	}
4276 	} /* switch (info_level) */
4277 
4278 	d_info->num_entry++;
4279 	d_info->out_buf_len -= next_entry_offset;
4280 	d_info->wptr += next_entry_offset;
4281 	return 0;
4282 }
4283 
4284 static bool __query_dir(struct dir_context *ctx, const char *name, int namlen,
4285 		       loff_t offset, u64 ino, unsigned int d_type)
4286 {
4287 	struct ksmbd_readdir_data	*buf;
4288 	struct smb2_query_dir_private	*priv;
4289 	struct ksmbd_dir_info		*d_info;
4290 	int				rc;
4291 
4292 	buf	= container_of(ctx, struct ksmbd_readdir_data, ctx);
4293 	priv	= buf->private;
4294 	d_info	= priv->d_info;
4295 
4296 	/* dot and dotdot entries are already reserved */
4297 	if (!strcmp(".", name) || !strcmp("..", name))
4298 		return true;
4299 	d_info->num_scan++;
4300 	if (ksmbd_share_veto_filename(priv->work->tcon->share_conf, name))
4301 		return true;
4302 	if (!match_pattern(name, namlen, priv->search_pattern))
4303 		return true;
4304 
4305 	d_info->name		= name;
4306 	d_info->name_len	= namlen;
4307 	rc = reserve_populate_dentry(d_info, priv->info_level);
4308 	if (rc)
4309 		return false;
4310 	if (d_info->flags & SMB2_RETURN_SINGLE_ENTRY)
4311 		d_info->out_buf_len = 0;
4312 	return true;
4313 }
4314 
4315 static int verify_info_level(int info_level)
4316 {
4317 	switch (info_level) {
4318 	case FILE_FULL_DIRECTORY_INFORMATION:
4319 	case FILE_BOTH_DIRECTORY_INFORMATION:
4320 	case FILE_DIRECTORY_INFORMATION:
4321 	case FILE_NAMES_INFORMATION:
4322 	case FILEID_FULL_DIRECTORY_INFORMATION:
4323 	case FILEID_BOTH_DIRECTORY_INFORMATION:
4324 	case SMB_FIND_FILE_POSIX_INFO:
4325 		break;
4326 	default:
4327 		return -EOPNOTSUPP;
4328 	}
4329 
4330 	return 0;
4331 }
4332 
4333 static int smb2_resp_buf_len(struct ksmbd_work *work, unsigned short hdr2_len)
4334 {
4335 	int free_len;
4336 
4337 	free_len = (int)(work->response_sz -
4338 		(get_rfc1002_len(work->response_buf) + 4)) - hdr2_len;
4339 	return free_len;
4340 }
4341 
4342 static int smb2_calc_max_out_buf_len(struct ksmbd_work *work,
4343 				     unsigned short hdr2_len,
4344 				     unsigned int out_buf_len)
4345 {
4346 	int free_len;
4347 
4348 	if (out_buf_len > work->conn->vals->max_trans_size)
4349 		return -EINVAL;
4350 
4351 	free_len = smb2_resp_buf_len(work, hdr2_len);
4352 	if (free_len < 0)
4353 		return -EINVAL;
4354 
4355 	return min_t(int, out_buf_len, free_len);
4356 }
4357 
4358 int smb2_query_dir(struct ksmbd_work *work)
4359 {
4360 	struct ksmbd_conn *conn = work->conn;
4361 	struct smb2_query_directory_req *req;
4362 	struct smb2_query_directory_rsp *rsp;
4363 	struct ksmbd_share_config *share = work->tcon->share_conf;
4364 	struct ksmbd_file *dir_fp = NULL;
4365 	struct ksmbd_dir_info d_info;
4366 	int rc = 0;
4367 	char *srch_ptr = NULL;
4368 	unsigned char srch_flag;
4369 	int buffer_sz;
4370 	struct smb2_query_dir_private query_dir_private = {NULL, };
4371 
4372 	ksmbd_debug(SMB, "Received smb2 query directory request\n");
4373 
4374 	WORK_BUFFERS(work, req, rsp);
4375 
4376 	if (ksmbd_override_fsids(work)) {
4377 		rsp->hdr.Status = STATUS_NO_MEMORY;
4378 		smb2_set_err_rsp(work);
4379 		return -ENOMEM;
4380 	}
4381 
4382 	rc = verify_info_level(req->FileInformationClass);
4383 	if (rc) {
4384 		rc = -EFAULT;
4385 		goto err_out2;
4386 	}
4387 
4388 	dir_fp = ksmbd_lookup_fd_slow(work, req->VolatileFileId, req->PersistentFileId);
4389 	if (!dir_fp) {
4390 		rc = -EBADF;
4391 		goto err_out2;
4392 	}
4393 
4394 	if (!(dir_fp->daccess & FILE_LIST_DIRECTORY_LE) ||
4395 	    inode_permission(file_mnt_idmap(dir_fp->filp),
4396 			     file_inode(dir_fp->filp),
4397 			     MAY_READ | MAY_EXEC)) {
4398 		pr_err("no right to enumerate directory (%pD)\n", dir_fp->filp);
4399 		rc = -EACCES;
4400 		goto err_out2;
4401 	}
4402 
4403 	if (!S_ISDIR(file_inode(dir_fp->filp)->i_mode)) {
4404 		pr_err("can't do query dir for a file\n");
4405 		rc = -EINVAL;
4406 		goto err_out2;
4407 	}
4408 
4409 	srch_flag = req->Flags;
4410 	srch_ptr = smb_strndup_from_utf16((char *)req + le16_to_cpu(req->FileNameOffset),
4411 					  le16_to_cpu(req->FileNameLength), 1,
4412 					  conn->local_nls);
4413 	if (IS_ERR(srch_ptr)) {
4414 		ksmbd_debug(SMB, "Search Pattern not found\n");
4415 		rc = -EINVAL;
4416 		goto err_out2;
4417 	} else {
4418 		ksmbd_debug(SMB, "Search pattern is %s\n", srch_ptr);
4419 	}
4420 
4421 	if (srch_flag & SMB2_REOPEN || srch_flag & SMB2_RESTART_SCANS) {
4422 		ksmbd_debug(SMB, "Restart directory scan\n");
4423 		generic_file_llseek(dir_fp->filp, 0, SEEK_SET);
4424 	}
4425 
4426 	memset(&d_info, 0, sizeof(struct ksmbd_dir_info));
4427 	d_info.wptr = (char *)rsp->Buffer;
4428 	d_info.rptr = (char *)rsp->Buffer;
4429 	d_info.out_buf_len =
4430 		smb2_calc_max_out_buf_len(work, 8,
4431 					  le32_to_cpu(req->OutputBufferLength));
4432 	if (d_info.out_buf_len < 0) {
4433 		rc = -EINVAL;
4434 		goto err_out;
4435 	}
4436 	d_info.flags = srch_flag;
4437 
4438 	/*
4439 	 * reserve dot and dotdot entries in head of buffer
4440 	 * in first response
4441 	 */
4442 	rc = ksmbd_populate_dot_dotdot_entries(work, req->FileInformationClass,
4443 					       dir_fp, &d_info, srch_ptr,
4444 					       smb2_populate_readdir_entry);
4445 	if (rc == -ENOSPC)
4446 		rc = 0;
4447 	else if (rc)
4448 		goto err_out;
4449 
4450 	if (test_share_config_flag(share, KSMBD_SHARE_FLAG_HIDE_DOT_FILES))
4451 		d_info.hide_dot_file = true;
4452 
4453 	buffer_sz				= d_info.out_buf_len;
4454 	d_info.rptr				= d_info.wptr;
4455 	query_dir_private.work			= work;
4456 	query_dir_private.search_pattern	= srch_ptr;
4457 	query_dir_private.dir_fp		= dir_fp;
4458 	query_dir_private.d_info		= &d_info;
4459 	query_dir_private.info_level		= req->FileInformationClass;
4460 	dir_fp->readdir_data.private		= &query_dir_private;
4461 	set_ctx_actor(&dir_fp->readdir_data.ctx, __query_dir);
4462 again:
4463 	d_info.num_scan = 0;
4464 	rc = iterate_dir(dir_fp->filp, &dir_fp->readdir_data.ctx);
4465 	/*
4466 	 * num_entry can be 0 if the directory iteration stops before reaching
4467 	 * the end of the directory and no file is matched with the search
4468 	 * pattern.
4469 	 */
4470 	if (rc >= 0 && !d_info.num_entry && d_info.num_scan &&
4471 	    d_info.out_buf_len > 0)
4472 		goto again;
4473 	/*
4474 	 * req->OutputBufferLength is too small to contain even one entry.
4475 	 * In this case, it immediately returns OutputBufferLength 0 to client.
4476 	 */
4477 	if (!d_info.out_buf_len && !d_info.num_entry)
4478 		goto no_buf_len;
4479 	if (rc > 0 || rc == -ENOSPC)
4480 		rc = 0;
4481 	else if (rc)
4482 		goto err_out;
4483 
4484 	d_info.wptr = d_info.rptr;
4485 	d_info.out_buf_len = buffer_sz;
4486 	rc = process_query_dir_entries(&query_dir_private);
4487 	if (rc)
4488 		goto err_out;
4489 
4490 	if (!d_info.data_count && d_info.out_buf_len >= 0) {
4491 		if (srch_flag & SMB2_RETURN_SINGLE_ENTRY && !is_asterisk(srch_ptr)) {
4492 			rsp->hdr.Status = STATUS_NO_SUCH_FILE;
4493 		} else {
4494 			dir_fp->dot_dotdot[0] = dir_fp->dot_dotdot[1] = 0;
4495 			rsp->hdr.Status = STATUS_NO_MORE_FILES;
4496 		}
4497 		rsp->StructureSize = cpu_to_le16(9);
4498 		rsp->OutputBufferOffset = cpu_to_le16(0);
4499 		rsp->OutputBufferLength = cpu_to_le32(0);
4500 		rsp->Buffer[0] = 0;
4501 		rc = ksmbd_iov_pin_rsp(work, (void *)rsp,
4502 				       offsetof(struct smb2_query_directory_rsp, Buffer)
4503 				       + 1);
4504 		if (rc)
4505 			goto err_out;
4506 	} else {
4507 no_buf_len:
4508 		((FILE_DIRECTORY_INFO *)
4509 		((char *)rsp->Buffer + d_info.last_entry_offset))
4510 		->NextEntryOffset = 0;
4511 		if (d_info.data_count >= d_info.last_entry_off_align)
4512 			d_info.data_count -= d_info.last_entry_off_align;
4513 
4514 		rsp->StructureSize = cpu_to_le16(9);
4515 		rsp->OutputBufferOffset = cpu_to_le16(72);
4516 		rsp->OutputBufferLength = cpu_to_le32(d_info.data_count);
4517 		rc = ksmbd_iov_pin_rsp(work, (void *)rsp,
4518 				       offsetof(struct smb2_query_directory_rsp, Buffer) +
4519 				       d_info.data_count);
4520 		if (rc)
4521 			goto err_out;
4522 	}
4523 
4524 	kfree(srch_ptr);
4525 	ksmbd_fd_put(work, dir_fp);
4526 	ksmbd_revert_fsids(work);
4527 	return 0;
4528 
4529 err_out:
4530 	pr_err("error while processing smb2 query dir rc = %d\n", rc);
4531 	kfree(srch_ptr);
4532 
4533 err_out2:
4534 	if (rc == -EINVAL)
4535 		rsp->hdr.Status = STATUS_INVALID_PARAMETER;
4536 	else if (rc == -EACCES)
4537 		rsp->hdr.Status = STATUS_ACCESS_DENIED;
4538 	else if (rc == -ENOENT)
4539 		rsp->hdr.Status = STATUS_NO_SUCH_FILE;
4540 	else if (rc == -EBADF)
4541 		rsp->hdr.Status = STATUS_FILE_CLOSED;
4542 	else if (rc == -ENOMEM)
4543 		rsp->hdr.Status = STATUS_NO_MEMORY;
4544 	else if (rc == -EFAULT)
4545 		rsp->hdr.Status = STATUS_INVALID_INFO_CLASS;
4546 	else if (rc == -EIO)
4547 		rsp->hdr.Status = STATUS_FILE_CORRUPT_ERROR;
4548 	if (!rsp->hdr.Status)
4549 		rsp->hdr.Status = STATUS_UNEXPECTED_IO_ERROR;
4550 
4551 	smb2_set_err_rsp(work);
4552 	ksmbd_fd_put(work, dir_fp);
4553 	ksmbd_revert_fsids(work);
4554 	return rc;
4555 }
4556 
4557 /**
4558  * buffer_check_err() - helper function to check buffer errors
4559  * @reqOutputBufferLength:	max buffer length expected in command response
4560  * @rsp:		query info response buffer contains output buffer length
4561  * @rsp_org:		base response buffer pointer in case of chained response
4562  *
4563  * Return:	0 on success, otherwise error
4564  */
4565 static int buffer_check_err(int reqOutputBufferLength,
4566 			    struct smb2_query_info_rsp *rsp,
4567 			    void *rsp_org)
4568 {
4569 	if (reqOutputBufferLength < le32_to_cpu(rsp->OutputBufferLength)) {
4570 		pr_err("Invalid Buffer Size Requested\n");
4571 		rsp->hdr.Status = STATUS_INFO_LENGTH_MISMATCH;
4572 		*(__be32 *)rsp_org = cpu_to_be32(sizeof(struct smb2_hdr));
4573 		return -EINVAL;
4574 	}
4575 	return 0;
4576 }
4577 
4578 static void get_standard_info_pipe(struct smb2_query_info_rsp *rsp,
4579 				   void *rsp_org)
4580 {
4581 	struct smb2_file_standard_info *sinfo;
4582 
4583 	sinfo = (struct smb2_file_standard_info *)rsp->Buffer;
4584 
4585 	sinfo->AllocationSize = cpu_to_le64(4096);
4586 	sinfo->EndOfFile = cpu_to_le64(0);
4587 	sinfo->NumberOfLinks = cpu_to_le32(1);
4588 	sinfo->DeletePending = 1;
4589 	sinfo->Directory = 0;
4590 	rsp->OutputBufferLength =
4591 		cpu_to_le32(sizeof(struct smb2_file_standard_info));
4592 }
4593 
4594 static void get_internal_info_pipe(struct smb2_query_info_rsp *rsp, u64 num,
4595 				   void *rsp_org)
4596 {
4597 	struct smb2_file_internal_info *file_info;
4598 
4599 	file_info = (struct smb2_file_internal_info *)rsp->Buffer;
4600 
4601 	/* any unique number */
4602 	file_info->IndexNumber = cpu_to_le64(num | (1ULL << 63));
4603 	rsp->OutputBufferLength =
4604 		cpu_to_le32(sizeof(struct smb2_file_internal_info));
4605 }
4606 
4607 static int smb2_get_info_file_pipe(struct ksmbd_session *sess,
4608 				   struct smb2_query_info_req *req,
4609 				   struct smb2_query_info_rsp *rsp,
4610 				   void *rsp_org)
4611 {
4612 	u64 id;
4613 	int rc;
4614 
4615 	/*
4616 	 * Windows can sometime send query file info request on
4617 	 * pipe without opening it, checking error condition here
4618 	 */
4619 	id = req->VolatileFileId;
4620 
4621 	lockdep_assert_not_held(&sess->rpc_lock);
4622 
4623 	down_read(&sess->rpc_lock);
4624 	if (!ksmbd_session_rpc_method(sess, id)) {
4625 		up_read(&sess->rpc_lock);
4626 		return -ENOENT;
4627 	}
4628 	up_read(&sess->rpc_lock);
4629 
4630 	ksmbd_debug(SMB, "FileInfoClass %u, FileId 0x%llx\n",
4631 		    req->FileInfoClass, req->VolatileFileId);
4632 
4633 	switch (req->FileInfoClass) {
4634 	case FILE_STANDARD_INFORMATION:
4635 		get_standard_info_pipe(rsp, rsp_org);
4636 		rc = buffer_check_err(le32_to_cpu(req->OutputBufferLength),
4637 				      rsp, rsp_org);
4638 		break;
4639 	case FILE_INTERNAL_INFORMATION:
4640 		get_internal_info_pipe(rsp, id, rsp_org);
4641 		rc = buffer_check_err(le32_to_cpu(req->OutputBufferLength),
4642 				      rsp, rsp_org);
4643 		break;
4644 	default:
4645 		ksmbd_debug(SMB, "smb2_info_file_pipe for %u not supported\n",
4646 			    req->FileInfoClass);
4647 		rc = -EOPNOTSUPP;
4648 	}
4649 	return rc;
4650 }
4651 
4652 /**
4653  * smb2_get_ea() - handler for smb2 get extended attribute command
4654  * @work:	smb work containing query info command buffer
4655  * @fp:		ksmbd_file pointer
4656  * @req:	get extended attribute request
4657  * @rsp:	response buffer pointer
4658  * @rsp_org:	base response buffer pointer in case of chained response
4659  *
4660  * Return:	0 on success, otherwise error
4661  */
4662 static int smb2_get_ea(struct ksmbd_work *work, struct ksmbd_file *fp,
4663 		       struct smb2_query_info_req *req,
4664 		       struct smb2_query_info_rsp *rsp, void *rsp_org)
4665 {
4666 	struct smb2_ea_info *eainfo, *prev_eainfo;
4667 	char *name, *ptr, *xattr_list = NULL, *buf;
4668 	int rc, name_len, value_len, xattr_list_len, idx;
4669 	ssize_t buf_free_len, alignment_bytes, next_offset, rsp_data_cnt = 0;
4670 	struct smb2_ea_info_req *ea_req = NULL;
4671 	const struct path *path;
4672 	struct mnt_idmap *idmap = file_mnt_idmap(fp->filp);
4673 
4674 	if (!(fp->daccess & FILE_READ_EA_LE)) {
4675 		pr_err("Not permitted to read ext attr : 0x%x\n",
4676 		       fp->daccess);
4677 		return -EACCES;
4678 	}
4679 
4680 	path = &fp->filp->f_path;
4681 	/* single EA entry is requested with given user.* name */
4682 	if (req->InputBufferLength) {
4683 		if (le32_to_cpu(req->InputBufferLength) <=
4684 		    sizeof(struct smb2_ea_info_req))
4685 			return -EINVAL;
4686 
4687 		ea_req = (struct smb2_ea_info_req *)((char *)req +
4688 						     le16_to_cpu(req->InputBufferOffset));
4689 	} else {
4690 		/* need to send all EAs, if no specific EA is requested*/
4691 		if (le32_to_cpu(req->Flags) & SL_RETURN_SINGLE_ENTRY)
4692 			ksmbd_debug(SMB,
4693 				    "All EAs are requested but need to send single EA entry in rsp flags 0x%x\n",
4694 				    le32_to_cpu(req->Flags));
4695 	}
4696 
4697 	buf_free_len =
4698 		smb2_calc_max_out_buf_len(work, 8,
4699 					  le32_to_cpu(req->OutputBufferLength));
4700 	if (buf_free_len < 0)
4701 		return -EINVAL;
4702 
4703 	rc = ksmbd_vfs_listxattr(path->dentry, &xattr_list);
4704 	if (rc < 0) {
4705 		rsp->hdr.Status = STATUS_INVALID_HANDLE;
4706 		goto out;
4707 	} else if (!rc) { /* there is no EA in the file */
4708 		ksmbd_debug(SMB, "no ea data in the file\n");
4709 		goto done;
4710 	}
4711 	xattr_list_len = rc;
4712 
4713 	ptr = (char *)rsp->Buffer;
4714 	eainfo = (struct smb2_ea_info *)ptr;
4715 	prev_eainfo = eainfo;
4716 	idx = 0;
4717 
4718 	while (idx < xattr_list_len) {
4719 		name = xattr_list + idx;
4720 		name_len = strlen(name);
4721 
4722 		ksmbd_debug(SMB, "%s, len %d\n", name, name_len);
4723 		idx += name_len + 1;
4724 
4725 		/*
4726 		 * CIFS does not support EA other than user.* namespace,
4727 		 * still keep the framework generic, to list other attrs
4728 		 * in future.
4729 		 */
4730 		if (strncmp(name, XATTR_USER_PREFIX, XATTR_USER_PREFIX_LEN))
4731 			continue;
4732 
4733 		if (!strncmp(&name[XATTR_USER_PREFIX_LEN], STREAM_PREFIX,
4734 			     STREAM_PREFIX_LEN))
4735 			continue;
4736 
4737 		if (req->InputBufferLength &&
4738 		    strncmp(&name[XATTR_USER_PREFIX_LEN], ea_req->name,
4739 			    ea_req->EaNameLength))
4740 			continue;
4741 
4742 		if (!strncmp(&name[XATTR_USER_PREFIX_LEN],
4743 			     DOS_ATTRIBUTE_PREFIX, DOS_ATTRIBUTE_PREFIX_LEN))
4744 			continue;
4745 
4746 		if (!strncmp(name, XATTR_USER_PREFIX, XATTR_USER_PREFIX_LEN))
4747 			name_len -= XATTR_USER_PREFIX_LEN;
4748 
4749 		ptr = eainfo->name + name_len + 1;
4750 		buf_free_len -= (offsetof(struct smb2_ea_info, name) +
4751 				name_len + 1);
4752 		/* bailout if xattr can't fit in buf_free_len */
4753 		value_len = ksmbd_vfs_getxattr(idmap, path->dentry,
4754 					       name, &buf);
4755 		if (value_len <= 0) {
4756 			rc = -ENOENT;
4757 			rsp->hdr.Status = STATUS_INVALID_HANDLE;
4758 			goto out;
4759 		}
4760 
4761 		buf_free_len -= value_len;
4762 		if (buf_free_len < 0) {
4763 			kfree(buf);
4764 			break;
4765 		}
4766 
4767 		memcpy(ptr, buf, value_len);
4768 		kfree(buf);
4769 
4770 		ptr += value_len;
4771 		eainfo->Flags = 0;
4772 		eainfo->EaNameLength = name_len;
4773 
4774 		if (!strncmp(name, XATTR_USER_PREFIX, XATTR_USER_PREFIX_LEN))
4775 			memcpy(eainfo->name, &name[XATTR_USER_PREFIX_LEN],
4776 			       name_len);
4777 		else
4778 			memcpy(eainfo->name, name, name_len);
4779 
4780 		eainfo->name[name_len] = '\0';
4781 		eainfo->EaValueLength = cpu_to_le16(value_len);
4782 		next_offset = offsetof(struct smb2_ea_info, name) +
4783 			name_len + 1 + value_len;
4784 
4785 		/* align next xattr entry at 4 byte bundary */
4786 		alignment_bytes = ((next_offset + 3) & ~3) - next_offset;
4787 		if (alignment_bytes) {
4788 			memset(ptr, '\0', alignment_bytes);
4789 			ptr += alignment_bytes;
4790 			next_offset += alignment_bytes;
4791 			buf_free_len -= alignment_bytes;
4792 		}
4793 		eainfo->NextEntryOffset = cpu_to_le32(next_offset);
4794 		prev_eainfo = eainfo;
4795 		eainfo = (struct smb2_ea_info *)ptr;
4796 		rsp_data_cnt += next_offset;
4797 
4798 		if (req->InputBufferLength) {
4799 			ksmbd_debug(SMB, "single entry requested\n");
4800 			break;
4801 		}
4802 	}
4803 
4804 	/* no more ea entries */
4805 	prev_eainfo->NextEntryOffset = 0;
4806 done:
4807 	rc = 0;
4808 	if (rsp_data_cnt == 0)
4809 		rsp->hdr.Status = STATUS_NO_EAS_ON_FILE;
4810 	rsp->OutputBufferLength = cpu_to_le32(rsp_data_cnt);
4811 out:
4812 	kvfree(xattr_list);
4813 	return rc;
4814 }
4815 
4816 static void get_file_access_info(struct smb2_query_info_rsp *rsp,
4817 				 struct ksmbd_file *fp, void *rsp_org)
4818 {
4819 	struct smb2_file_access_info *file_info;
4820 
4821 	file_info = (struct smb2_file_access_info *)rsp->Buffer;
4822 	file_info->AccessFlags = fp->daccess;
4823 	rsp->OutputBufferLength =
4824 		cpu_to_le32(sizeof(struct smb2_file_access_info));
4825 }
4826 
4827 static int get_file_basic_info(struct smb2_query_info_rsp *rsp,
4828 			       struct ksmbd_file *fp, void *rsp_org)
4829 {
4830 	struct smb2_file_basic_info *basic_info;
4831 	struct kstat stat;
4832 	u64 time;
4833 	int ret;
4834 
4835 	if (!(fp->daccess & FILE_READ_ATTRIBUTES_LE)) {
4836 		pr_err("no right to read the attributes : 0x%x\n",
4837 		       fp->daccess);
4838 		return -EACCES;
4839 	}
4840 
4841 	ret = vfs_getattr(&fp->filp->f_path, &stat, STATX_BASIC_STATS,
4842 			  AT_STATX_SYNC_AS_STAT);
4843 	if (ret)
4844 		return ret;
4845 
4846 	basic_info = (struct smb2_file_basic_info *)rsp->Buffer;
4847 	basic_info->CreationTime = cpu_to_le64(fp->create_time);
4848 	time = ksmbd_UnixTimeToNT(stat.atime);
4849 	basic_info->LastAccessTime = cpu_to_le64(time);
4850 	time = ksmbd_UnixTimeToNT(stat.mtime);
4851 	basic_info->LastWriteTime = cpu_to_le64(time);
4852 	time = ksmbd_UnixTimeToNT(stat.ctime);
4853 	basic_info->ChangeTime = cpu_to_le64(time);
4854 	basic_info->Attributes = fp->f_ci->m_fattr;
4855 	basic_info->Pad1 = 0;
4856 	rsp->OutputBufferLength =
4857 		cpu_to_le32(sizeof(struct smb2_file_basic_info));
4858 	return 0;
4859 }
4860 
4861 static int get_file_standard_info(struct smb2_query_info_rsp *rsp,
4862 				  struct ksmbd_file *fp, void *rsp_org)
4863 {
4864 	struct smb2_file_standard_info *sinfo;
4865 	unsigned int delete_pending;
4866 	struct kstat stat;
4867 	int ret;
4868 
4869 	ret = vfs_getattr(&fp->filp->f_path, &stat, STATX_BASIC_STATS,
4870 			  AT_STATX_SYNC_AS_STAT);
4871 	if (ret)
4872 		return ret;
4873 
4874 	sinfo = (struct smb2_file_standard_info *)rsp->Buffer;
4875 	delete_pending = ksmbd_inode_pending_delete(fp);
4876 
4877 	if (ksmbd_stream_fd(fp) == false) {
4878 		sinfo->AllocationSize = cpu_to_le64(stat.blocks << 9);
4879 		sinfo->EndOfFile = S_ISDIR(stat.mode) ? 0 : cpu_to_le64(stat.size);
4880 	} else {
4881 		sinfo->AllocationSize = cpu_to_le64(fp->stream.size);
4882 		sinfo->EndOfFile = cpu_to_le64(fp->stream.size);
4883 	}
4884 	sinfo->NumberOfLinks = cpu_to_le32(get_nlink(&stat) - delete_pending);
4885 	sinfo->DeletePending = delete_pending;
4886 	sinfo->Directory = S_ISDIR(stat.mode) ? 1 : 0;
4887 	rsp->OutputBufferLength =
4888 		cpu_to_le32(sizeof(struct smb2_file_standard_info));
4889 
4890 	return 0;
4891 }
4892 
4893 static void get_file_alignment_info(struct smb2_query_info_rsp *rsp,
4894 				    void *rsp_org)
4895 {
4896 	struct smb2_file_alignment_info *file_info;
4897 
4898 	file_info = (struct smb2_file_alignment_info *)rsp->Buffer;
4899 	file_info->AlignmentRequirement = 0;
4900 	rsp->OutputBufferLength =
4901 		cpu_to_le32(sizeof(struct smb2_file_alignment_info));
4902 }
4903 
4904 static int get_file_all_info(struct ksmbd_work *work,
4905 			     struct smb2_query_info_rsp *rsp,
4906 			     struct ksmbd_file *fp,
4907 			     void *rsp_org)
4908 {
4909 	struct ksmbd_conn *conn = work->conn;
4910 	struct smb2_file_all_info *file_info;
4911 	unsigned int delete_pending;
4912 	struct kstat stat;
4913 	int conv_len;
4914 	char *filename;
4915 	u64 time;
4916 	int ret;
4917 
4918 	if (!(fp->daccess & FILE_READ_ATTRIBUTES_LE)) {
4919 		ksmbd_debug(SMB, "no right to read the attributes : 0x%x\n",
4920 			    fp->daccess);
4921 		return -EACCES;
4922 	}
4923 
4924 	filename = convert_to_nt_pathname(work->tcon->share_conf, &fp->filp->f_path);
4925 	if (IS_ERR(filename))
4926 		return PTR_ERR(filename);
4927 
4928 	ret = vfs_getattr(&fp->filp->f_path, &stat, STATX_BASIC_STATS,
4929 			  AT_STATX_SYNC_AS_STAT);
4930 	if (ret) {
4931 		kfree(filename);
4932 		return ret;
4933 	}
4934 
4935 	ksmbd_debug(SMB, "filename = %s\n", filename);
4936 	delete_pending = ksmbd_inode_pending_delete(fp);
4937 	file_info = (struct smb2_file_all_info *)rsp->Buffer;
4938 
4939 	file_info->CreationTime = cpu_to_le64(fp->create_time);
4940 	time = ksmbd_UnixTimeToNT(stat.atime);
4941 	file_info->LastAccessTime = cpu_to_le64(time);
4942 	time = ksmbd_UnixTimeToNT(stat.mtime);
4943 	file_info->LastWriteTime = cpu_to_le64(time);
4944 	time = ksmbd_UnixTimeToNT(stat.ctime);
4945 	file_info->ChangeTime = cpu_to_le64(time);
4946 	file_info->Attributes = fp->f_ci->m_fattr;
4947 	file_info->Pad1 = 0;
4948 	if (ksmbd_stream_fd(fp) == false) {
4949 		file_info->AllocationSize =
4950 			cpu_to_le64(stat.blocks << 9);
4951 		file_info->EndOfFile = S_ISDIR(stat.mode) ? 0 : cpu_to_le64(stat.size);
4952 	} else {
4953 		file_info->AllocationSize = cpu_to_le64(fp->stream.size);
4954 		file_info->EndOfFile = cpu_to_le64(fp->stream.size);
4955 	}
4956 	file_info->NumberOfLinks =
4957 			cpu_to_le32(get_nlink(&stat) - delete_pending);
4958 	file_info->DeletePending = delete_pending;
4959 	file_info->Directory = S_ISDIR(stat.mode) ? 1 : 0;
4960 	file_info->Pad2 = 0;
4961 	file_info->IndexNumber = cpu_to_le64(stat.ino);
4962 	file_info->EASize = 0;
4963 	file_info->AccessFlags = fp->daccess;
4964 	if (ksmbd_stream_fd(fp) == false)
4965 		file_info->CurrentByteOffset = cpu_to_le64(fp->filp->f_pos);
4966 	else
4967 		file_info->CurrentByteOffset = cpu_to_le64(fp->stream.pos);
4968 	file_info->Mode = fp->coption;
4969 	file_info->AlignmentRequirement = 0;
4970 	conv_len = smbConvertToUTF16((__le16 *)file_info->FileName, filename,
4971 				     PATH_MAX, conn->local_nls, 0);
4972 	conv_len *= 2;
4973 	file_info->FileNameLength = cpu_to_le32(conv_len);
4974 	rsp->OutputBufferLength =
4975 		cpu_to_le32(sizeof(struct smb2_file_all_info) + conv_len - 1);
4976 	kfree(filename);
4977 	return 0;
4978 }
4979 
4980 static void get_file_alternate_info(struct ksmbd_work *work,
4981 				    struct smb2_query_info_rsp *rsp,
4982 				    struct ksmbd_file *fp,
4983 				    void *rsp_org)
4984 {
4985 	struct ksmbd_conn *conn = work->conn;
4986 	struct smb2_file_alt_name_info *file_info;
4987 	struct dentry *dentry = fp->filp->f_path.dentry;
4988 	int conv_len;
4989 
4990 	spin_lock(&dentry->d_lock);
4991 	file_info = (struct smb2_file_alt_name_info *)rsp->Buffer;
4992 	conv_len = ksmbd_extract_shortname(conn,
4993 					   dentry->d_name.name,
4994 					   file_info->FileName);
4995 	spin_unlock(&dentry->d_lock);
4996 	file_info->FileNameLength = cpu_to_le32(conv_len);
4997 	rsp->OutputBufferLength =
4998 		cpu_to_le32(struct_size(file_info, FileName, conv_len));
4999 }
5000 
5001 static int get_file_stream_info(struct ksmbd_work *work,
5002 				struct smb2_query_info_rsp *rsp,
5003 				struct ksmbd_file *fp,
5004 				void *rsp_org)
5005 {
5006 	struct ksmbd_conn *conn = work->conn;
5007 	struct smb2_file_stream_info *file_info;
5008 	char *stream_name, *xattr_list = NULL, *stream_buf;
5009 	struct kstat stat;
5010 	const struct path *path = &fp->filp->f_path;
5011 	ssize_t xattr_list_len;
5012 	int nbytes = 0, streamlen, stream_name_len, next, idx = 0;
5013 	int buf_free_len;
5014 	struct smb2_query_info_req *req = ksmbd_req_buf_next(work);
5015 	int ret;
5016 
5017 	ret = vfs_getattr(&fp->filp->f_path, &stat, STATX_BASIC_STATS,
5018 			  AT_STATX_SYNC_AS_STAT);
5019 	if (ret)
5020 		return ret;
5021 
5022 	file_info = (struct smb2_file_stream_info *)rsp->Buffer;
5023 
5024 	buf_free_len =
5025 		smb2_calc_max_out_buf_len(work, 8,
5026 					  le32_to_cpu(req->OutputBufferLength));
5027 	if (buf_free_len < 0)
5028 		goto out;
5029 
5030 	xattr_list_len = ksmbd_vfs_listxattr(path->dentry, &xattr_list);
5031 	if (xattr_list_len < 0) {
5032 		goto out;
5033 	} else if (!xattr_list_len) {
5034 		ksmbd_debug(SMB, "empty xattr in the file\n");
5035 		goto out;
5036 	}
5037 
5038 	while (idx < xattr_list_len) {
5039 		stream_name = xattr_list + idx;
5040 		streamlen = strlen(stream_name);
5041 		idx += streamlen + 1;
5042 
5043 		ksmbd_debug(SMB, "%s, len %d\n", stream_name, streamlen);
5044 
5045 		if (strncmp(&stream_name[XATTR_USER_PREFIX_LEN],
5046 			    STREAM_PREFIX, STREAM_PREFIX_LEN))
5047 			continue;
5048 
5049 		stream_name_len = streamlen - (XATTR_USER_PREFIX_LEN +
5050 				STREAM_PREFIX_LEN);
5051 		streamlen = stream_name_len;
5052 
5053 		/* plus : size */
5054 		streamlen += 1;
5055 		stream_buf = kmalloc(streamlen + 1, KSMBD_DEFAULT_GFP);
5056 		if (!stream_buf)
5057 			break;
5058 
5059 		streamlen = snprintf(stream_buf, streamlen + 1,
5060 				     ":%s", &stream_name[XATTR_NAME_STREAM_LEN]);
5061 
5062 		next = sizeof(struct smb2_file_stream_info) + streamlen * 2;
5063 		if (next > buf_free_len) {
5064 			kfree(stream_buf);
5065 			break;
5066 		}
5067 
5068 		file_info = (struct smb2_file_stream_info *)&rsp->Buffer[nbytes];
5069 		streamlen  = smbConvertToUTF16((__le16 *)file_info->StreamName,
5070 					       stream_buf, streamlen,
5071 					       conn->local_nls, 0);
5072 		streamlen *= 2;
5073 		kfree(stream_buf);
5074 		file_info->StreamNameLength = cpu_to_le32(streamlen);
5075 		file_info->StreamSize = cpu_to_le64(stream_name_len);
5076 		file_info->StreamAllocationSize = cpu_to_le64(stream_name_len);
5077 
5078 		nbytes += next;
5079 		buf_free_len -= next;
5080 		file_info->NextEntryOffset = cpu_to_le32(next);
5081 	}
5082 
5083 out:
5084 	if (!S_ISDIR(stat.mode) &&
5085 	    buf_free_len >= sizeof(struct smb2_file_stream_info) + 7 * 2) {
5086 		file_info = (struct smb2_file_stream_info *)
5087 			&rsp->Buffer[nbytes];
5088 		streamlen = smbConvertToUTF16((__le16 *)file_info->StreamName,
5089 					      "::$DATA", 7, conn->local_nls, 0);
5090 		streamlen *= 2;
5091 		file_info->StreamNameLength = cpu_to_le32(streamlen);
5092 		file_info->StreamSize = cpu_to_le64(stat.size);
5093 		file_info->StreamAllocationSize = cpu_to_le64(stat.blocks << 9);
5094 		nbytes += sizeof(struct smb2_file_stream_info) + streamlen;
5095 	}
5096 
5097 	/* last entry offset should be 0 */
5098 	file_info->NextEntryOffset = 0;
5099 	kvfree(xattr_list);
5100 
5101 	rsp->OutputBufferLength = cpu_to_le32(nbytes);
5102 
5103 	return 0;
5104 }
5105 
5106 static int get_file_internal_info(struct smb2_query_info_rsp *rsp,
5107 				  struct ksmbd_file *fp, void *rsp_org)
5108 {
5109 	struct smb2_file_internal_info *file_info;
5110 	struct kstat stat;
5111 	int ret;
5112 
5113 	ret = vfs_getattr(&fp->filp->f_path, &stat, STATX_BASIC_STATS,
5114 			  AT_STATX_SYNC_AS_STAT);
5115 	if (ret)
5116 		return ret;
5117 
5118 	file_info = (struct smb2_file_internal_info *)rsp->Buffer;
5119 	file_info->IndexNumber = cpu_to_le64(stat.ino);
5120 	rsp->OutputBufferLength =
5121 		cpu_to_le32(sizeof(struct smb2_file_internal_info));
5122 
5123 	return 0;
5124 }
5125 
5126 static int get_file_network_open_info(struct smb2_query_info_rsp *rsp,
5127 				      struct ksmbd_file *fp, void *rsp_org)
5128 {
5129 	struct smb2_file_network_open_info *file_info;
5130 	struct kstat stat;
5131 	u64 time;
5132 	int ret;
5133 
5134 	if (!(fp->daccess & FILE_READ_ATTRIBUTES_LE)) {
5135 		pr_err("no right to read the attributes : 0x%x\n",
5136 		       fp->daccess);
5137 		return -EACCES;
5138 	}
5139 
5140 	ret = vfs_getattr(&fp->filp->f_path, &stat, STATX_BASIC_STATS,
5141 			  AT_STATX_SYNC_AS_STAT);
5142 	if (ret)
5143 		return ret;
5144 
5145 	file_info = (struct smb2_file_network_open_info *)rsp->Buffer;
5146 
5147 	file_info->CreationTime = cpu_to_le64(fp->create_time);
5148 	time = ksmbd_UnixTimeToNT(stat.atime);
5149 	file_info->LastAccessTime = cpu_to_le64(time);
5150 	time = ksmbd_UnixTimeToNT(stat.mtime);
5151 	file_info->LastWriteTime = cpu_to_le64(time);
5152 	time = ksmbd_UnixTimeToNT(stat.ctime);
5153 	file_info->ChangeTime = cpu_to_le64(time);
5154 	file_info->Attributes = fp->f_ci->m_fattr;
5155 	if (ksmbd_stream_fd(fp) == false) {
5156 		file_info->AllocationSize = cpu_to_le64(stat.blocks << 9);
5157 		file_info->EndOfFile = S_ISDIR(stat.mode) ? 0 : cpu_to_le64(stat.size);
5158 	} else {
5159 		file_info->AllocationSize = cpu_to_le64(fp->stream.size);
5160 		file_info->EndOfFile = cpu_to_le64(fp->stream.size);
5161 	}
5162 	file_info->Reserved = cpu_to_le32(0);
5163 	rsp->OutputBufferLength =
5164 		cpu_to_le32(sizeof(struct smb2_file_network_open_info));
5165 	return 0;
5166 }
5167 
5168 static void get_file_ea_info(struct smb2_query_info_rsp *rsp, void *rsp_org)
5169 {
5170 	struct smb2_file_ea_info *file_info;
5171 
5172 	file_info = (struct smb2_file_ea_info *)rsp->Buffer;
5173 	file_info->EASize = 0;
5174 	rsp->OutputBufferLength =
5175 		cpu_to_le32(sizeof(struct smb2_file_ea_info));
5176 }
5177 
5178 static void get_file_position_info(struct smb2_query_info_rsp *rsp,
5179 				   struct ksmbd_file *fp, void *rsp_org)
5180 {
5181 	struct smb2_file_pos_info *file_info;
5182 
5183 	file_info = (struct smb2_file_pos_info *)rsp->Buffer;
5184 	if (ksmbd_stream_fd(fp) == false)
5185 		file_info->CurrentByteOffset = cpu_to_le64(fp->filp->f_pos);
5186 	else
5187 		file_info->CurrentByteOffset = cpu_to_le64(fp->stream.pos);
5188 
5189 	rsp->OutputBufferLength =
5190 		cpu_to_le32(sizeof(struct smb2_file_pos_info));
5191 }
5192 
5193 static void get_file_mode_info(struct smb2_query_info_rsp *rsp,
5194 			       struct ksmbd_file *fp, void *rsp_org)
5195 {
5196 	struct smb2_file_mode_info *file_info;
5197 
5198 	file_info = (struct smb2_file_mode_info *)rsp->Buffer;
5199 	file_info->Mode = fp->coption & FILE_MODE_INFO_MASK;
5200 	rsp->OutputBufferLength =
5201 		cpu_to_le32(sizeof(struct smb2_file_mode_info));
5202 }
5203 
5204 static int get_file_compression_info(struct smb2_query_info_rsp *rsp,
5205 				     struct ksmbd_file *fp, void *rsp_org)
5206 {
5207 	struct smb2_file_comp_info *file_info;
5208 	struct kstat stat;
5209 	int ret;
5210 
5211 	ret = vfs_getattr(&fp->filp->f_path, &stat, STATX_BASIC_STATS,
5212 			  AT_STATX_SYNC_AS_STAT);
5213 	if (ret)
5214 		return ret;
5215 
5216 	file_info = (struct smb2_file_comp_info *)rsp->Buffer;
5217 	file_info->CompressedFileSize = cpu_to_le64(stat.blocks << 9);
5218 	file_info->CompressionFormat = COMPRESSION_FORMAT_NONE;
5219 	file_info->CompressionUnitShift = 0;
5220 	file_info->ChunkShift = 0;
5221 	file_info->ClusterShift = 0;
5222 	memset(&file_info->Reserved[0], 0, 3);
5223 
5224 	rsp->OutputBufferLength =
5225 		cpu_to_le32(sizeof(struct smb2_file_comp_info));
5226 
5227 	return 0;
5228 }
5229 
5230 static int get_file_attribute_tag_info(struct smb2_query_info_rsp *rsp,
5231 				       struct ksmbd_file *fp, void *rsp_org)
5232 {
5233 	struct smb2_file_attr_tag_info *file_info;
5234 
5235 	if (!(fp->daccess & FILE_READ_ATTRIBUTES_LE)) {
5236 		pr_err("no right to read the attributes : 0x%x\n",
5237 		       fp->daccess);
5238 		return -EACCES;
5239 	}
5240 
5241 	file_info = (struct smb2_file_attr_tag_info *)rsp->Buffer;
5242 	file_info->FileAttributes = fp->f_ci->m_fattr;
5243 	file_info->ReparseTag = 0;
5244 	rsp->OutputBufferLength =
5245 		cpu_to_le32(sizeof(struct smb2_file_attr_tag_info));
5246 	return 0;
5247 }
5248 
5249 static int find_file_posix_info(struct smb2_query_info_rsp *rsp,
5250 				struct ksmbd_file *fp, void *rsp_org)
5251 {
5252 	struct smb311_posix_qinfo *file_info;
5253 	struct inode *inode = file_inode(fp->filp);
5254 	struct mnt_idmap *idmap = file_mnt_idmap(fp->filp);
5255 	vfsuid_t vfsuid = i_uid_into_vfsuid(idmap, inode);
5256 	vfsgid_t vfsgid = i_gid_into_vfsgid(idmap, inode);
5257 	struct kstat stat;
5258 	u64 time;
5259 	int out_buf_len = sizeof(struct smb311_posix_qinfo) + 32;
5260 	int ret;
5261 
5262 	ret = vfs_getattr(&fp->filp->f_path, &stat, STATX_BASIC_STATS,
5263 			  AT_STATX_SYNC_AS_STAT);
5264 	if (ret)
5265 		return ret;
5266 
5267 	file_info = (struct smb311_posix_qinfo *)rsp->Buffer;
5268 	file_info->CreationTime = cpu_to_le64(fp->create_time);
5269 	time = ksmbd_UnixTimeToNT(stat.atime);
5270 	file_info->LastAccessTime = cpu_to_le64(time);
5271 	time = ksmbd_UnixTimeToNT(stat.mtime);
5272 	file_info->LastWriteTime = cpu_to_le64(time);
5273 	time = ksmbd_UnixTimeToNT(stat.ctime);
5274 	file_info->ChangeTime = cpu_to_le64(time);
5275 	file_info->DosAttributes = fp->f_ci->m_fattr;
5276 	file_info->Inode = cpu_to_le64(stat.ino);
5277 	if (ksmbd_stream_fd(fp) == false) {
5278 		file_info->EndOfFile = cpu_to_le64(stat.size);
5279 		file_info->AllocationSize = cpu_to_le64(stat.blocks << 9);
5280 	} else {
5281 		file_info->EndOfFile = cpu_to_le64(fp->stream.size);
5282 		file_info->AllocationSize = cpu_to_le64(fp->stream.size);
5283 	}
5284 	file_info->HardLinks = cpu_to_le32(stat.nlink);
5285 	file_info->Mode = cpu_to_le32(stat.mode & 0777);
5286 	switch (stat.mode & S_IFMT) {
5287 	case S_IFDIR:
5288 		file_info->Mode |= cpu_to_le32(POSIX_TYPE_DIR << POSIX_FILETYPE_SHIFT);
5289 		break;
5290 	case S_IFLNK:
5291 		file_info->Mode |= cpu_to_le32(POSIX_TYPE_SYMLINK << POSIX_FILETYPE_SHIFT);
5292 		break;
5293 	case S_IFCHR:
5294 		file_info->Mode |= cpu_to_le32(POSIX_TYPE_CHARDEV << POSIX_FILETYPE_SHIFT);
5295 		break;
5296 	case S_IFBLK:
5297 		file_info->Mode |= cpu_to_le32(POSIX_TYPE_BLKDEV << POSIX_FILETYPE_SHIFT);
5298 		break;
5299 	case S_IFIFO:
5300 		file_info->Mode |= cpu_to_le32(POSIX_TYPE_FIFO << POSIX_FILETYPE_SHIFT);
5301 		break;
5302 	case S_IFSOCK:
5303 		file_info->Mode |= cpu_to_le32(POSIX_TYPE_SOCKET << POSIX_FILETYPE_SHIFT);
5304 	}
5305 
5306 	file_info->DeviceId = cpu_to_le32(stat.rdev);
5307 
5308 	/*
5309 	 * Sids(32) contain two sids(Domain sid(16), UNIX group sid(16)).
5310 	 * UNIX sid(16) = revision(1) + num_subauth(1) + authority(6) +
5311 	 *		  sub_auth(4 * 1(num_subauth)) + RID(4).
5312 	 */
5313 	id_to_sid(from_kuid_munged(&init_user_ns, vfsuid_into_kuid(vfsuid)),
5314 		  SIDUNIX_USER, (struct smb_sid *)&file_info->Sids[0]);
5315 	id_to_sid(from_kgid_munged(&init_user_ns, vfsgid_into_kgid(vfsgid)),
5316 		  SIDUNIX_GROUP, (struct smb_sid *)&file_info->Sids[16]);
5317 
5318 	rsp->OutputBufferLength = cpu_to_le32(out_buf_len);
5319 
5320 	return 0;
5321 }
5322 
5323 static int smb2_get_info_file(struct ksmbd_work *work,
5324 			      struct smb2_query_info_req *req,
5325 			      struct smb2_query_info_rsp *rsp)
5326 {
5327 	struct ksmbd_file *fp;
5328 	int fileinfoclass = 0;
5329 	int rc = 0;
5330 	unsigned int id = KSMBD_NO_FID, pid = KSMBD_NO_FID;
5331 
5332 	if (test_share_config_flag(work->tcon->share_conf,
5333 				   KSMBD_SHARE_FLAG_PIPE)) {
5334 		/* smb2 info file called for pipe */
5335 		return smb2_get_info_file_pipe(work->sess, req, rsp,
5336 					       work->response_buf);
5337 	}
5338 
5339 	if (work->next_smb2_rcv_hdr_off) {
5340 		if (!has_file_id(req->VolatileFileId)) {
5341 			ksmbd_debug(SMB, "Compound request set FID = %llu\n",
5342 				    work->compound_fid);
5343 			id = work->compound_fid;
5344 			pid = work->compound_pfid;
5345 		}
5346 	}
5347 
5348 	if (!has_file_id(id)) {
5349 		id = req->VolatileFileId;
5350 		pid = req->PersistentFileId;
5351 	}
5352 
5353 	fp = ksmbd_lookup_fd_slow(work, id, pid);
5354 	if (!fp)
5355 		return -ENOENT;
5356 
5357 	fileinfoclass = req->FileInfoClass;
5358 
5359 	switch (fileinfoclass) {
5360 	case FILE_ACCESS_INFORMATION:
5361 		get_file_access_info(rsp, fp, work->response_buf);
5362 		break;
5363 
5364 	case FILE_BASIC_INFORMATION:
5365 		rc = get_file_basic_info(rsp, fp, work->response_buf);
5366 		break;
5367 
5368 	case FILE_STANDARD_INFORMATION:
5369 		rc = get_file_standard_info(rsp, fp, work->response_buf);
5370 		break;
5371 
5372 	case FILE_ALIGNMENT_INFORMATION:
5373 		get_file_alignment_info(rsp, work->response_buf);
5374 		break;
5375 
5376 	case FILE_ALL_INFORMATION:
5377 		rc = get_file_all_info(work, rsp, fp, work->response_buf);
5378 		break;
5379 
5380 	case FILE_ALTERNATE_NAME_INFORMATION:
5381 		get_file_alternate_info(work, rsp, fp, work->response_buf);
5382 		break;
5383 
5384 	case FILE_STREAM_INFORMATION:
5385 		rc = get_file_stream_info(work, rsp, fp, work->response_buf);
5386 		break;
5387 
5388 	case FILE_INTERNAL_INFORMATION:
5389 		rc = get_file_internal_info(rsp, fp, work->response_buf);
5390 		break;
5391 
5392 	case FILE_NETWORK_OPEN_INFORMATION:
5393 		rc = get_file_network_open_info(rsp, fp, work->response_buf);
5394 		break;
5395 
5396 	case FILE_EA_INFORMATION:
5397 		get_file_ea_info(rsp, work->response_buf);
5398 		break;
5399 
5400 	case FILE_FULL_EA_INFORMATION:
5401 		rc = smb2_get_ea(work, fp, req, rsp, work->response_buf);
5402 		break;
5403 
5404 	case FILE_POSITION_INFORMATION:
5405 		get_file_position_info(rsp, fp, work->response_buf);
5406 		break;
5407 
5408 	case FILE_MODE_INFORMATION:
5409 		get_file_mode_info(rsp, fp, work->response_buf);
5410 		break;
5411 
5412 	case FILE_COMPRESSION_INFORMATION:
5413 		rc = get_file_compression_info(rsp, fp, work->response_buf);
5414 		break;
5415 
5416 	case FILE_ATTRIBUTE_TAG_INFORMATION:
5417 		rc = get_file_attribute_tag_info(rsp, fp, work->response_buf);
5418 		break;
5419 	case SMB_FIND_FILE_POSIX_INFO:
5420 		if (!work->tcon->posix_extensions) {
5421 			pr_err("client doesn't negotiate with SMB3.1.1 POSIX Extensions\n");
5422 			rc = -EOPNOTSUPP;
5423 		} else {
5424 			rc = find_file_posix_info(rsp, fp, work->response_buf);
5425 		}
5426 		break;
5427 	default:
5428 		ksmbd_debug(SMB, "fileinfoclass %d not supported yet\n",
5429 			    fileinfoclass);
5430 		rc = -EOPNOTSUPP;
5431 	}
5432 	if (!rc)
5433 		rc = buffer_check_err(le32_to_cpu(req->OutputBufferLength),
5434 				      rsp, work->response_buf);
5435 	ksmbd_fd_put(work, fp);
5436 	return rc;
5437 }
5438 
5439 static int smb2_get_info_filesystem(struct ksmbd_work *work,
5440 				    struct smb2_query_info_req *req,
5441 				    struct smb2_query_info_rsp *rsp)
5442 {
5443 	struct ksmbd_session *sess = work->sess;
5444 	struct ksmbd_conn *conn = work->conn;
5445 	struct ksmbd_share_config *share = work->tcon->share_conf;
5446 	int fsinfoclass = 0;
5447 	struct kstatfs stfs;
5448 	struct path path;
5449 	int rc = 0, len;
5450 
5451 	if (!share->path)
5452 		return -EIO;
5453 
5454 	rc = kern_path(share->path, LOOKUP_NO_SYMLINKS, &path);
5455 	if (rc) {
5456 		pr_err("cannot create vfs path\n");
5457 		return -EIO;
5458 	}
5459 
5460 	rc = vfs_statfs(&path, &stfs);
5461 	if (rc) {
5462 		pr_err("cannot do stat of path %s\n", share->path);
5463 		path_put(&path);
5464 		return -EIO;
5465 	}
5466 
5467 	fsinfoclass = req->FileInfoClass;
5468 
5469 	switch (fsinfoclass) {
5470 	case FS_DEVICE_INFORMATION:
5471 	{
5472 		FILE_SYSTEM_DEVICE_INFO *info;
5473 
5474 		info = (FILE_SYSTEM_DEVICE_INFO *)rsp->Buffer;
5475 
5476 		info->DeviceType = cpu_to_le32(FILE_DEVICE_DISK);
5477 		info->DeviceCharacteristics =
5478 			cpu_to_le32(FILE_DEVICE_IS_MOUNTED);
5479 		if (!test_tree_conn_flag(work->tcon,
5480 					 KSMBD_TREE_CONN_FLAG_WRITABLE))
5481 			info->DeviceCharacteristics |=
5482 				cpu_to_le32(FILE_READ_ONLY_DEVICE);
5483 		rsp->OutputBufferLength = cpu_to_le32(8);
5484 		break;
5485 	}
5486 	case FS_ATTRIBUTE_INFORMATION:
5487 	{
5488 		FILE_SYSTEM_ATTRIBUTE_INFO *info;
5489 		size_t sz;
5490 
5491 		info = (FILE_SYSTEM_ATTRIBUTE_INFO *)rsp->Buffer;
5492 		info->Attributes = cpu_to_le32(FILE_SUPPORTS_OBJECT_IDS |
5493 					       FILE_PERSISTENT_ACLS |
5494 					       FILE_UNICODE_ON_DISK |
5495 					       FILE_CASE_PRESERVED_NAMES |
5496 					       FILE_CASE_SENSITIVE_SEARCH |
5497 					       FILE_SUPPORTS_BLOCK_REFCOUNTING);
5498 
5499 		info->Attributes |= cpu_to_le32(server_conf.share_fake_fscaps);
5500 
5501 		if (test_share_config_flag(work->tcon->share_conf,
5502 		    KSMBD_SHARE_FLAG_STREAMS))
5503 			info->Attributes |= cpu_to_le32(FILE_NAMED_STREAMS);
5504 
5505 		info->MaxPathNameComponentLength = cpu_to_le32(stfs.f_namelen);
5506 		/*
5507 		 * some application(potableapp) can not run on ksmbd share
5508 		 * because only NTFS handle security setting on windows.
5509 		 * So Although local fs(EXT4 or F2fs, etc) is not NTFS,
5510 		 * ksmbd should show share as NTFS. Later, If needed, we can add
5511 		 * fs type(s) parameter to change fs type user wanted.
5512 		 */
5513 		len = smbConvertToUTF16((__le16 *)info->FileSystemName,
5514 					"NTFS", PATH_MAX, conn->local_nls, 0);
5515 		len = len * 2;
5516 		info->FileSystemNameLen = cpu_to_le32(len);
5517 		sz = sizeof(FILE_SYSTEM_ATTRIBUTE_INFO) + len;
5518 		rsp->OutputBufferLength = cpu_to_le32(sz);
5519 		break;
5520 	}
5521 	case FS_VOLUME_INFORMATION:
5522 	{
5523 		struct filesystem_vol_info *info;
5524 		size_t sz;
5525 		unsigned int serial_crc = 0;
5526 
5527 		info = (struct filesystem_vol_info *)(rsp->Buffer);
5528 		info->VolumeCreationTime = 0;
5529 		serial_crc = crc32_le(serial_crc, share->name,
5530 				      strlen(share->name));
5531 		serial_crc = crc32_le(serial_crc, share->path,
5532 				      strlen(share->path));
5533 		serial_crc = crc32_le(serial_crc, ksmbd_netbios_name(),
5534 				      strlen(ksmbd_netbios_name()));
5535 		/* Taking dummy value of serial number*/
5536 		info->SerialNumber = cpu_to_le32(serial_crc);
5537 		len = smbConvertToUTF16((__le16 *)info->VolumeLabel,
5538 					share->name, PATH_MAX,
5539 					conn->local_nls, 0);
5540 		len = len * 2;
5541 		info->VolumeLabelSize = cpu_to_le32(len);
5542 		info->Reserved = 0;
5543 		sz = sizeof(struct filesystem_vol_info) + len;
5544 		rsp->OutputBufferLength = cpu_to_le32(sz);
5545 		break;
5546 	}
5547 	case FS_SIZE_INFORMATION:
5548 	{
5549 		FILE_SYSTEM_SIZE_INFO *info;
5550 
5551 		info = (FILE_SYSTEM_SIZE_INFO *)(rsp->Buffer);
5552 		info->TotalAllocationUnits = cpu_to_le64(stfs.f_blocks);
5553 		info->AvailableAllocationUnits = cpu_to_le64(stfs.f_bfree);
5554 		info->SectorsPerAllocationUnit = cpu_to_le32(1);
5555 		info->BytesPerSector = cpu_to_le32(stfs.f_bsize);
5556 		rsp->OutputBufferLength = cpu_to_le32(24);
5557 		break;
5558 	}
5559 	case FS_FULL_SIZE_INFORMATION:
5560 	{
5561 		struct smb2_fs_full_size_info *info;
5562 
5563 		info = (struct smb2_fs_full_size_info *)(rsp->Buffer);
5564 		info->TotalAllocationUnits = cpu_to_le64(stfs.f_blocks);
5565 		info->CallerAvailableAllocationUnits =
5566 					cpu_to_le64(stfs.f_bavail);
5567 		info->ActualAvailableAllocationUnits =
5568 					cpu_to_le64(stfs.f_bfree);
5569 		info->SectorsPerAllocationUnit = cpu_to_le32(1);
5570 		info->BytesPerSector = cpu_to_le32(stfs.f_bsize);
5571 		rsp->OutputBufferLength = cpu_to_le32(32);
5572 		break;
5573 	}
5574 	case FS_OBJECT_ID_INFORMATION:
5575 	{
5576 		struct object_id_info *info;
5577 
5578 		info = (struct object_id_info *)(rsp->Buffer);
5579 
5580 		if (!user_guest(sess->user))
5581 			memcpy(info->objid, user_passkey(sess->user), 16);
5582 		else
5583 			memset(info->objid, 0, 16);
5584 
5585 		info->extended_info.magic = cpu_to_le32(EXTENDED_INFO_MAGIC);
5586 		info->extended_info.version = cpu_to_le32(1);
5587 		info->extended_info.release = cpu_to_le32(1);
5588 		info->extended_info.rel_date = 0;
5589 		memcpy(info->extended_info.version_string, "1.1.0", strlen("1.1.0"));
5590 		rsp->OutputBufferLength = cpu_to_le32(64);
5591 		break;
5592 	}
5593 	case FS_SECTOR_SIZE_INFORMATION:
5594 	{
5595 		struct smb3_fs_ss_info *info;
5596 		unsigned int sector_size =
5597 			min_t(unsigned int, path.mnt->mnt_sb->s_blocksize, 4096);
5598 
5599 		info = (struct smb3_fs_ss_info *)(rsp->Buffer);
5600 
5601 		info->LogicalBytesPerSector = cpu_to_le32(sector_size);
5602 		info->PhysicalBytesPerSectorForAtomicity =
5603 				cpu_to_le32(sector_size);
5604 		info->PhysicalBytesPerSectorForPerf = cpu_to_le32(sector_size);
5605 		info->FSEffPhysicalBytesPerSectorForAtomicity =
5606 				cpu_to_le32(sector_size);
5607 		info->Flags = cpu_to_le32(SSINFO_FLAGS_ALIGNED_DEVICE |
5608 				    SSINFO_FLAGS_PARTITION_ALIGNED_ON_DEVICE);
5609 		info->ByteOffsetForSectorAlignment = 0;
5610 		info->ByteOffsetForPartitionAlignment = 0;
5611 		rsp->OutputBufferLength = cpu_to_le32(28);
5612 		break;
5613 	}
5614 	case FS_CONTROL_INFORMATION:
5615 	{
5616 		/*
5617 		 * TODO : The current implementation is based on
5618 		 * test result with win7(NTFS) server. It's need to
5619 		 * modify this to get valid Quota values
5620 		 * from Linux kernel
5621 		 */
5622 		struct smb2_fs_control_info *info;
5623 
5624 		info = (struct smb2_fs_control_info *)(rsp->Buffer);
5625 		info->FreeSpaceStartFiltering = 0;
5626 		info->FreeSpaceThreshold = 0;
5627 		info->FreeSpaceStopFiltering = 0;
5628 		info->DefaultQuotaThreshold = cpu_to_le64(SMB2_NO_FID);
5629 		info->DefaultQuotaLimit = cpu_to_le64(SMB2_NO_FID);
5630 		info->Padding = 0;
5631 		rsp->OutputBufferLength = cpu_to_le32(48);
5632 		break;
5633 	}
5634 	case FS_POSIX_INFORMATION:
5635 	{
5636 		FILE_SYSTEM_POSIX_INFO *info;
5637 
5638 		if (!work->tcon->posix_extensions) {
5639 			pr_err("client doesn't negotiate with SMB3.1.1 POSIX Extensions\n");
5640 			path_put(&path);
5641 			return -EOPNOTSUPP;
5642 		} else {
5643 			info = (FILE_SYSTEM_POSIX_INFO *)(rsp->Buffer);
5644 			info->OptimalTransferSize = cpu_to_le32(stfs.f_bsize);
5645 			info->BlockSize = cpu_to_le32(stfs.f_bsize);
5646 			info->TotalBlocks = cpu_to_le64(stfs.f_blocks);
5647 			info->BlocksAvail = cpu_to_le64(stfs.f_bfree);
5648 			info->UserBlocksAvail = cpu_to_le64(stfs.f_bavail);
5649 			info->TotalFileNodes = cpu_to_le64(stfs.f_files);
5650 			info->FreeFileNodes = cpu_to_le64(stfs.f_ffree);
5651 			rsp->OutputBufferLength = cpu_to_le32(56);
5652 		}
5653 		break;
5654 	}
5655 	default:
5656 		path_put(&path);
5657 		return -EOPNOTSUPP;
5658 	}
5659 	rc = buffer_check_err(le32_to_cpu(req->OutputBufferLength),
5660 			      rsp, work->response_buf);
5661 	path_put(&path);
5662 	return rc;
5663 }
5664 
5665 static int smb2_get_info_sec(struct ksmbd_work *work,
5666 			     struct smb2_query_info_req *req,
5667 			     struct smb2_query_info_rsp *rsp)
5668 {
5669 	struct ksmbd_file *fp;
5670 	struct mnt_idmap *idmap;
5671 	struct smb_ntsd *pntsd = (struct smb_ntsd *)rsp->Buffer, *ppntsd = NULL;
5672 	struct smb_fattr fattr = {{0}};
5673 	struct inode *inode;
5674 	__u32 secdesclen = 0;
5675 	unsigned int id = KSMBD_NO_FID, pid = KSMBD_NO_FID;
5676 	int addition_info = le32_to_cpu(req->AdditionalInformation);
5677 	int rc = 0, ppntsd_size = 0;
5678 
5679 	if (addition_info & ~(OWNER_SECINFO | GROUP_SECINFO | DACL_SECINFO |
5680 			      PROTECTED_DACL_SECINFO |
5681 			      UNPROTECTED_DACL_SECINFO)) {
5682 		ksmbd_debug(SMB, "Unsupported addition info: 0x%x)\n",
5683 		       addition_info);
5684 
5685 		pntsd->revision = cpu_to_le16(1);
5686 		pntsd->type = cpu_to_le16(SELF_RELATIVE | DACL_PROTECTED);
5687 		pntsd->osidoffset = 0;
5688 		pntsd->gsidoffset = 0;
5689 		pntsd->sacloffset = 0;
5690 		pntsd->dacloffset = 0;
5691 
5692 		secdesclen = sizeof(struct smb_ntsd);
5693 		rsp->OutputBufferLength = cpu_to_le32(secdesclen);
5694 
5695 		return 0;
5696 	}
5697 
5698 	if (work->next_smb2_rcv_hdr_off) {
5699 		if (!has_file_id(req->VolatileFileId)) {
5700 			ksmbd_debug(SMB, "Compound request set FID = %llu\n",
5701 				    work->compound_fid);
5702 			id = work->compound_fid;
5703 			pid = work->compound_pfid;
5704 		}
5705 	}
5706 
5707 	if (!has_file_id(id)) {
5708 		id = req->VolatileFileId;
5709 		pid = req->PersistentFileId;
5710 	}
5711 
5712 	fp = ksmbd_lookup_fd_slow(work, id, pid);
5713 	if (!fp)
5714 		return -ENOENT;
5715 
5716 	idmap = file_mnt_idmap(fp->filp);
5717 	inode = file_inode(fp->filp);
5718 	ksmbd_acls_fattr(&fattr, idmap, inode);
5719 
5720 	if (test_share_config_flag(work->tcon->share_conf,
5721 				   KSMBD_SHARE_FLAG_ACL_XATTR))
5722 		ppntsd_size = ksmbd_vfs_get_sd_xattr(work->conn, idmap,
5723 						     fp->filp->f_path.dentry,
5724 						     &ppntsd);
5725 
5726 	/* Check if sd buffer size exceeds response buffer size */
5727 	if (smb2_resp_buf_len(work, 8) > ppntsd_size)
5728 		rc = build_sec_desc(idmap, pntsd, ppntsd, ppntsd_size,
5729 				    addition_info, &secdesclen, &fattr);
5730 	posix_acl_release(fattr.cf_acls);
5731 	posix_acl_release(fattr.cf_dacls);
5732 	kfree(ppntsd);
5733 	ksmbd_fd_put(work, fp);
5734 	if (rc)
5735 		return rc;
5736 
5737 	rsp->OutputBufferLength = cpu_to_le32(secdesclen);
5738 	return 0;
5739 }
5740 
5741 /**
5742  * smb2_query_info() - handler for smb2 query info command
5743  * @work:	smb work containing query info request buffer
5744  *
5745  * Return:	0 on success, otherwise error
5746  */
5747 int smb2_query_info(struct ksmbd_work *work)
5748 {
5749 	struct smb2_query_info_req *req;
5750 	struct smb2_query_info_rsp *rsp;
5751 	int rc = 0;
5752 
5753 	ksmbd_debug(SMB, "Received request smb2 query info request\n");
5754 
5755 	WORK_BUFFERS(work, req, rsp);
5756 
5757 	if (ksmbd_override_fsids(work)) {
5758 		rc = -ENOMEM;
5759 		goto err_out;
5760 	}
5761 
5762 	switch (req->InfoType) {
5763 	case SMB2_O_INFO_FILE:
5764 		ksmbd_debug(SMB, "GOT SMB2_O_INFO_FILE\n");
5765 		rc = smb2_get_info_file(work, req, rsp);
5766 		break;
5767 	case SMB2_O_INFO_FILESYSTEM:
5768 		ksmbd_debug(SMB, "GOT SMB2_O_INFO_FILESYSTEM\n");
5769 		rc = smb2_get_info_filesystem(work, req, rsp);
5770 		break;
5771 	case SMB2_O_INFO_SECURITY:
5772 		ksmbd_debug(SMB, "GOT SMB2_O_INFO_SECURITY\n");
5773 		rc = smb2_get_info_sec(work, req, rsp);
5774 		break;
5775 	default:
5776 		ksmbd_debug(SMB, "InfoType %d not supported yet\n",
5777 			    req->InfoType);
5778 		rc = -EOPNOTSUPP;
5779 	}
5780 	ksmbd_revert_fsids(work);
5781 
5782 	if (!rc) {
5783 		rsp->StructureSize = cpu_to_le16(9);
5784 		rsp->OutputBufferOffset = cpu_to_le16(72);
5785 		rc = ksmbd_iov_pin_rsp(work, (void *)rsp,
5786 				       offsetof(struct smb2_query_info_rsp, Buffer) +
5787 					le32_to_cpu(rsp->OutputBufferLength));
5788 	}
5789 
5790 err_out:
5791 	if (rc < 0) {
5792 		if (rc == -EACCES)
5793 			rsp->hdr.Status = STATUS_ACCESS_DENIED;
5794 		else if (rc == -ENOENT)
5795 			rsp->hdr.Status = STATUS_FILE_CLOSED;
5796 		else if (rc == -EIO)
5797 			rsp->hdr.Status = STATUS_UNEXPECTED_IO_ERROR;
5798 		else if (rc == -ENOMEM)
5799 			rsp->hdr.Status = STATUS_INSUFFICIENT_RESOURCES;
5800 		else if (rc == -EOPNOTSUPP || rsp->hdr.Status == 0)
5801 			rsp->hdr.Status = STATUS_INVALID_INFO_CLASS;
5802 		smb2_set_err_rsp(work);
5803 
5804 		ksmbd_debug(SMB, "error while processing smb2 query rc = %d\n",
5805 			    rc);
5806 		return rc;
5807 	}
5808 	return 0;
5809 }
5810 
5811 /**
5812  * smb2_close_pipe() - handler for closing IPC pipe
5813  * @work:	smb work containing close request buffer
5814  *
5815  * Return:	0
5816  */
5817 static noinline int smb2_close_pipe(struct ksmbd_work *work)
5818 {
5819 	u64 id;
5820 	struct smb2_close_req *req;
5821 	struct smb2_close_rsp *rsp;
5822 
5823 	WORK_BUFFERS(work, req, rsp);
5824 
5825 	id = req->VolatileFileId;
5826 	ksmbd_session_rpc_close(work->sess, id);
5827 
5828 	rsp->StructureSize = cpu_to_le16(60);
5829 	rsp->Flags = 0;
5830 	rsp->Reserved = 0;
5831 	rsp->CreationTime = 0;
5832 	rsp->LastAccessTime = 0;
5833 	rsp->LastWriteTime = 0;
5834 	rsp->ChangeTime = 0;
5835 	rsp->AllocationSize = 0;
5836 	rsp->EndOfFile = 0;
5837 	rsp->Attributes = 0;
5838 
5839 	return ksmbd_iov_pin_rsp(work, (void *)rsp,
5840 				 sizeof(struct smb2_close_rsp));
5841 }
5842 
5843 /**
5844  * smb2_close() - handler for smb2 close file command
5845  * @work:	smb work containing close request buffer
5846  *
5847  * Return:	0 on success, otherwise error
5848  */
5849 int smb2_close(struct ksmbd_work *work)
5850 {
5851 	u64 volatile_id = KSMBD_NO_FID;
5852 	u64 sess_id;
5853 	struct smb2_close_req *req;
5854 	struct smb2_close_rsp *rsp;
5855 	struct ksmbd_conn *conn = work->conn;
5856 	struct ksmbd_file *fp;
5857 	u64 time;
5858 	int err = 0;
5859 
5860 	ksmbd_debug(SMB, "Received smb2 close request\n");
5861 
5862 	WORK_BUFFERS(work, req, rsp);
5863 
5864 	if (test_share_config_flag(work->tcon->share_conf,
5865 				   KSMBD_SHARE_FLAG_PIPE)) {
5866 		ksmbd_debug(SMB, "IPC pipe close request\n");
5867 		return smb2_close_pipe(work);
5868 	}
5869 
5870 	sess_id = le64_to_cpu(req->hdr.SessionId);
5871 	if (req->hdr.Flags & SMB2_FLAGS_RELATED_OPERATIONS)
5872 		sess_id = work->compound_sid;
5873 
5874 	work->compound_sid = 0;
5875 	if (check_session_id(conn, sess_id)) {
5876 		work->compound_sid = sess_id;
5877 	} else {
5878 		rsp->hdr.Status = STATUS_USER_SESSION_DELETED;
5879 		if (req->hdr.Flags & SMB2_FLAGS_RELATED_OPERATIONS)
5880 			rsp->hdr.Status = STATUS_INVALID_PARAMETER;
5881 		err = -EBADF;
5882 		goto out;
5883 	}
5884 
5885 	if (work->next_smb2_rcv_hdr_off &&
5886 	    !has_file_id(req->VolatileFileId)) {
5887 		if (!has_file_id(work->compound_fid)) {
5888 			/* file already closed, return FILE_CLOSED */
5889 			ksmbd_debug(SMB, "file already closed\n");
5890 			rsp->hdr.Status = STATUS_FILE_CLOSED;
5891 			err = -EBADF;
5892 			goto out;
5893 		} else {
5894 			ksmbd_debug(SMB,
5895 				    "Compound request set FID = %llu:%llu\n",
5896 				    work->compound_fid,
5897 				    work->compound_pfid);
5898 			volatile_id = work->compound_fid;
5899 
5900 			/* file closed, stored id is not valid anymore */
5901 			work->compound_fid = KSMBD_NO_FID;
5902 			work->compound_pfid = KSMBD_NO_FID;
5903 		}
5904 	} else {
5905 		volatile_id = req->VolatileFileId;
5906 	}
5907 	ksmbd_debug(SMB, "volatile_id = %llu\n", volatile_id);
5908 
5909 	rsp->StructureSize = cpu_to_le16(60);
5910 	rsp->Reserved = 0;
5911 
5912 	if (req->Flags == SMB2_CLOSE_FLAG_POSTQUERY_ATTRIB) {
5913 		struct kstat stat;
5914 		int ret;
5915 
5916 		fp = ksmbd_lookup_fd_fast(work, volatile_id);
5917 		if (!fp) {
5918 			err = -ENOENT;
5919 			goto out;
5920 		}
5921 
5922 		ret = vfs_getattr(&fp->filp->f_path, &stat, STATX_BASIC_STATS,
5923 				  AT_STATX_SYNC_AS_STAT);
5924 		if (ret) {
5925 			ksmbd_fd_put(work, fp);
5926 			goto out;
5927 		}
5928 
5929 		rsp->Flags = SMB2_CLOSE_FLAG_POSTQUERY_ATTRIB;
5930 		rsp->AllocationSize = S_ISDIR(stat.mode) ? 0 :
5931 			cpu_to_le64(stat.blocks << 9);
5932 		rsp->EndOfFile = cpu_to_le64(stat.size);
5933 		rsp->Attributes = fp->f_ci->m_fattr;
5934 		rsp->CreationTime = cpu_to_le64(fp->create_time);
5935 		time = ksmbd_UnixTimeToNT(stat.atime);
5936 		rsp->LastAccessTime = cpu_to_le64(time);
5937 		time = ksmbd_UnixTimeToNT(stat.mtime);
5938 		rsp->LastWriteTime = cpu_to_le64(time);
5939 		time = ksmbd_UnixTimeToNT(stat.ctime);
5940 		rsp->ChangeTime = cpu_to_le64(time);
5941 		ksmbd_fd_put(work, fp);
5942 	} else {
5943 		rsp->Flags = 0;
5944 		rsp->AllocationSize = 0;
5945 		rsp->EndOfFile = 0;
5946 		rsp->Attributes = 0;
5947 		rsp->CreationTime = 0;
5948 		rsp->LastAccessTime = 0;
5949 		rsp->LastWriteTime = 0;
5950 		rsp->ChangeTime = 0;
5951 	}
5952 
5953 	err = ksmbd_close_fd(work, volatile_id);
5954 out:
5955 	if (!err)
5956 		err = ksmbd_iov_pin_rsp(work, (void *)rsp,
5957 					sizeof(struct smb2_close_rsp));
5958 
5959 	if (err) {
5960 		if (rsp->hdr.Status == 0)
5961 			rsp->hdr.Status = STATUS_FILE_CLOSED;
5962 		smb2_set_err_rsp(work);
5963 	}
5964 
5965 	return err;
5966 }
5967 
5968 /**
5969  * smb2_echo() - handler for smb2 echo(ping) command
5970  * @work:	smb work containing echo request buffer
5971  *
5972  * Return:	0 on success, otherwise error
5973  */
5974 int smb2_echo(struct ksmbd_work *work)
5975 {
5976 	struct smb2_echo_rsp *rsp = smb_get_msg(work->response_buf);
5977 
5978 	ksmbd_debug(SMB, "Received smb2 echo request\n");
5979 
5980 	if (work->next_smb2_rcv_hdr_off)
5981 		rsp = ksmbd_resp_buf_next(work);
5982 
5983 	rsp->StructureSize = cpu_to_le16(4);
5984 	rsp->Reserved = 0;
5985 	return ksmbd_iov_pin_rsp(work, rsp, sizeof(struct smb2_echo_rsp));
5986 }
5987 
5988 static int smb2_rename(struct ksmbd_work *work,
5989 		       struct ksmbd_file *fp,
5990 		       struct smb2_file_rename_info *file_info,
5991 		       struct nls_table *local_nls)
5992 {
5993 	struct ksmbd_share_config *share = fp->tcon->share_conf;
5994 	char *new_name = NULL;
5995 	int rc, flags = 0;
5996 
5997 	ksmbd_debug(SMB, "setting FILE_RENAME_INFO\n");
5998 	new_name = smb2_get_name(file_info->FileName,
5999 				 le32_to_cpu(file_info->FileNameLength),
6000 				 local_nls);
6001 	if (IS_ERR(new_name))
6002 		return PTR_ERR(new_name);
6003 
6004 	if (fp->is_posix_ctxt == false && strchr(new_name, ':')) {
6005 		int s_type;
6006 		char *xattr_stream_name, *stream_name = NULL;
6007 		size_t xattr_stream_size;
6008 		int len;
6009 
6010 		rc = parse_stream_name(new_name, &stream_name, &s_type);
6011 		if (rc < 0)
6012 			goto out;
6013 
6014 		len = strlen(new_name);
6015 		if (len > 0 && new_name[len - 1] != '/') {
6016 			pr_err("not allow base filename in rename\n");
6017 			rc = -ESHARE;
6018 			goto out;
6019 		}
6020 
6021 		rc = ksmbd_vfs_xattr_stream_name(stream_name,
6022 						 &xattr_stream_name,
6023 						 &xattr_stream_size,
6024 						 s_type);
6025 		if (rc)
6026 			goto out;
6027 
6028 		rc = ksmbd_vfs_setxattr(file_mnt_idmap(fp->filp),
6029 					&fp->filp->f_path,
6030 					xattr_stream_name,
6031 					NULL, 0, 0, true);
6032 		if (rc < 0) {
6033 			pr_err("failed to store stream name in xattr: %d\n",
6034 			       rc);
6035 			rc = -EINVAL;
6036 			goto out;
6037 		}
6038 
6039 		goto out;
6040 	}
6041 
6042 	ksmbd_debug(SMB, "new name %s\n", new_name);
6043 	if (ksmbd_share_veto_filename(share, new_name)) {
6044 		rc = -ENOENT;
6045 		ksmbd_debug(SMB, "Can't rename vetoed file: %s\n", new_name);
6046 		goto out;
6047 	}
6048 
6049 	if (!file_info->ReplaceIfExists)
6050 		flags = RENAME_NOREPLACE;
6051 
6052 	rc = ksmbd_vfs_rename(work, &fp->filp->f_path, new_name, flags);
6053 	if (!rc)
6054 		smb_break_all_levII_oplock(work, fp, 0);
6055 out:
6056 	kfree(new_name);
6057 	return rc;
6058 }
6059 
6060 static int smb2_create_link(struct ksmbd_work *work,
6061 			    struct ksmbd_share_config *share,
6062 			    struct smb2_file_link_info *file_info,
6063 			    unsigned int buf_len, struct file *filp,
6064 			    struct nls_table *local_nls)
6065 {
6066 	char *link_name = NULL, *target_name = NULL, *pathname = NULL;
6067 	struct path path;
6068 	int rc;
6069 
6070 	if (buf_len < (u64)sizeof(struct smb2_file_link_info) +
6071 			le32_to_cpu(file_info->FileNameLength))
6072 		return -EINVAL;
6073 
6074 	ksmbd_debug(SMB, "setting FILE_LINK_INFORMATION\n");
6075 	pathname = kmalloc(PATH_MAX, KSMBD_DEFAULT_GFP);
6076 	if (!pathname)
6077 		return -ENOMEM;
6078 
6079 	link_name = smb2_get_name(file_info->FileName,
6080 				  le32_to_cpu(file_info->FileNameLength),
6081 				  local_nls);
6082 	if (IS_ERR(link_name) || S_ISDIR(file_inode(filp)->i_mode)) {
6083 		rc = -EINVAL;
6084 		goto out;
6085 	}
6086 
6087 	ksmbd_debug(SMB, "link name is %s\n", link_name);
6088 	target_name = file_path(filp, pathname, PATH_MAX);
6089 	if (IS_ERR(target_name)) {
6090 		rc = -EINVAL;
6091 		goto out;
6092 	}
6093 
6094 	ksmbd_debug(SMB, "target name is %s\n", target_name);
6095 	rc = ksmbd_vfs_kern_path_start_removing(work, link_name, LOOKUP_NO_SYMLINKS,
6096 						&path, 0);
6097 	if (rc) {
6098 		if (rc != -ENOENT)
6099 			goto out;
6100 	} else {
6101 		if (file_info->ReplaceIfExists) {
6102 			rc = ksmbd_vfs_remove_file(work, &path);
6103 			if (rc) {
6104 				rc = -EINVAL;
6105 				ksmbd_debug(SMB, "cannot delete %s\n",
6106 					    link_name);
6107 				goto out;
6108 			}
6109 		} else {
6110 			rc = -EEXIST;
6111 			ksmbd_debug(SMB, "link already exists\n");
6112 			goto out;
6113 		}
6114 		ksmbd_vfs_kern_path_end_removing(&path);
6115 	}
6116 	rc = ksmbd_vfs_link(work, target_name, link_name);
6117 	if (rc)
6118 		rc = -EINVAL;
6119 out:
6120 
6121 	if (!IS_ERR(link_name))
6122 		kfree(link_name);
6123 	kfree(pathname);
6124 	return rc;
6125 }
6126 
6127 static int set_file_basic_info(struct ksmbd_file *fp,
6128 			       struct smb2_file_basic_info *file_info,
6129 			       struct ksmbd_share_config *share)
6130 {
6131 	struct iattr attrs;
6132 	struct file *filp;
6133 	struct inode *inode;
6134 	struct mnt_idmap *idmap;
6135 	int rc = 0;
6136 
6137 	if (!(fp->daccess & FILE_WRITE_ATTRIBUTES_LE))
6138 		return -EACCES;
6139 
6140 	attrs.ia_valid = 0;
6141 	filp = fp->filp;
6142 	inode = file_inode(filp);
6143 	idmap = file_mnt_idmap(filp);
6144 
6145 	if (file_info->CreationTime)
6146 		fp->create_time = le64_to_cpu(file_info->CreationTime);
6147 
6148 	if (file_info->LastAccessTime) {
6149 		attrs.ia_atime = ksmbd_NTtimeToUnix(file_info->LastAccessTime);
6150 		attrs.ia_valid |= (ATTR_ATIME | ATTR_ATIME_SET);
6151 	}
6152 
6153 	if (file_info->ChangeTime)
6154 		inode_set_ctime_to_ts(inode,
6155 				ksmbd_NTtimeToUnix(file_info->ChangeTime));
6156 
6157 	if (file_info->LastWriteTime) {
6158 		attrs.ia_mtime = ksmbd_NTtimeToUnix(file_info->LastWriteTime);
6159 		attrs.ia_valid |= (ATTR_MTIME | ATTR_MTIME_SET | ATTR_CTIME);
6160 	}
6161 
6162 	if (file_info->Attributes) {
6163 		if (!S_ISDIR(inode->i_mode) &&
6164 		    file_info->Attributes & FILE_ATTRIBUTE_DIRECTORY_LE) {
6165 			pr_err("can't change a file to a directory\n");
6166 			return -EINVAL;
6167 		}
6168 
6169 		if (!(S_ISDIR(inode->i_mode) && file_info->Attributes == FILE_ATTRIBUTE_NORMAL_LE))
6170 			fp->f_ci->m_fattr = file_info->Attributes |
6171 				(fp->f_ci->m_fattr & FILE_ATTRIBUTE_DIRECTORY_LE);
6172 	}
6173 
6174 	if (test_share_config_flag(share, KSMBD_SHARE_FLAG_STORE_DOS_ATTRS) &&
6175 	    (file_info->CreationTime || file_info->Attributes)) {
6176 		struct xattr_dos_attrib da = {0};
6177 
6178 		da.version = 4;
6179 		da.itime = fp->itime;
6180 		da.create_time = fp->create_time;
6181 		da.attr = le32_to_cpu(fp->f_ci->m_fattr);
6182 		da.flags = XATTR_DOSINFO_ATTRIB | XATTR_DOSINFO_CREATE_TIME |
6183 			XATTR_DOSINFO_ITIME;
6184 
6185 		rc = ksmbd_vfs_set_dos_attrib_xattr(idmap, &filp->f_path, &da,
6186 				true);
6187 		if (rc)
6188 			ksmbd_debug(SMB,
6189 				    "failed to restore file attribute in EA\n");
6190 		rc = 0;
6191 	}
6192 
6193 	if (attrs.ia_valid) {
6194 		struct dentry *dentry = filp->f_path.dentry;
6195 		struct inode *inode = d_inode(dentry);
6196 
6197 		if (IS_IMMUTABLE(inode) || IS_APPEND(inode))
6198 			return -EACCES;
6199 
6200 		inode_lock(inode);
6201 		rc = notify_change(idmap, dentry, &attrs, NULL);
6202 		inode_unlock(inode);
6203 	}
6204 	return rc;
6205 }
6206 
6207 static int set_file_allocation_info(struct ksmbd_work *work,
6208 				    struct ksmbd_file *fp,
6209 				    struct smb2_file_alloc_info *file_alloc_info)
6210 {
6211 	/*
6212 	 * TODO : It's working fine only when store dos attributes
6213 	 * is not yes. need to implement a logic which works
6214 	 * properly with any smb.conf option
6215 	 */
6216 
6217 	loff_t alloc_blks;
6218 	struct inode *inode;
6219 	struct kstat stat;
6220 	int rc;
6221 
6222 	if (!(fp->daccess & FILE_WRITE_DATA_LE))
6223 		return -EACCES;
6224 
6225 	if (ksmbd_stream_fd(fp) == true)
6226 		return 0;
6227 
6228 	rc = vfs_getattr(&fp->filp->f_path, &stat, STATX_BASIC_STATS,
6229 			 AT_STATX_SYNC_AS_STAT);
6230 	if (rc)
6231 		return rc;
6232 
6233 	alloc_blks = (le64_to_cpu(file_alloc_info->AllocationSize) + 511) >> 9;
6234 	inode = file_inode(fp->filp);
6235 
6236 	if (alloc_blks > stat.blocks) {
6237 		smb_break_all_levII_oplock(work, fp, 1);
6238 		rc = vfs_fallocate(fp->filp, FALLOC_FL_KEEP_SIZE, 0,
6239 				   alloc_blks * 512);
6240 		if (rc && rc != -EOPNOTSUPP) {
6241 			pr_err("vfs_fallocate is failed : %d\n", rc);
6242 			return rc;
6243 		}
6244 	} else if (alloc_blks < stat.blocks) {
6245 		loff_t size;
6246 
6247 		/*
6248 		 * Allocation size could be smaller than original one
6249 		 * which means allocated blocks in file should be
6250 		 * deallocated. use truncate to cut out it, but inode
6251 		 * size is also updated with truncate offset.
6252 		 * inode size is retained by backup inode size.
6253 		 */
6254 		size = i_size_read(inode);
6255 		rc = ksmbd_vfs_truncate(work, fp, alloc_blks * 512);
6256 		if (rc) {
6257 			pr_err("truncate failed!, err %d\n", rc);
6258 			return rc;
6259 		}
6260 		if (size < alloc_blks * 512)
6261 			i_size_write(inode, size);
6262 	}
6263 	return 0;
6264 }
6265 
6266 static int set_end_of_file_info(struct ksmbd_work *work, struct ksmbd_file *fp,
6267 				struct smb2_file_eof_info *file_eof_info)
6268 {
6269 	loff_t newsize;
6270 	struct inode *inode;
6271 	int rc;
6272 
6273 	if (!(fp->daccess & FILE_WRITE_DATA_LE))
6274 		return -EACCES;
6275 
6276 	newsize = le64_to_cpu(file_eof_info->EndOfFile);
6277 	inode = file_inode(fp->filp);
6278 
6279 	/*
6280 	 * If FILE_END_OF_FILE_INFORMATION of set_info_file is called
6281 	 * on FAT32 shared device, truncate execution time is too long
6282 	 * and network error could cause from windows client. because
6283 	 * truncate of some filesystem like FAT32 fill zero data in
6284 	 * truncated range.
6285 	 */
6286 	if (inode->i_sb->s_magic != MSDOS_SUPER_MAGIC &&
6287 	    ksmbd_stream_fd(fp) == false) {
6288 		ksmbd_debug(SMB, "truncated to newsize %lld\n", newsize);
6289 		rc = ksmbd_vfs_truncate(work, fp, newsize);
6290 		if (rc) {
6291 			ksmbd_debug(SMB, "truncate failed!, err %d\n", rc);
6292 			if (rc != -EAGAIN)
6293 				rc = -EBADF;
6294 			return rc;
6295 		}
6296 	}
6297 	return 0;
6298 }
6299 
6300 static int set_rename_info(struct ksmbd_work *work, struct ksmbd_file *fp,
6301 			   struct smb2_file_rename_info *rename_info,
6302 			   unsigned int buf_len)
6303 {
6304 	if (!(fp->daccess & FILE_DELETE_LE)) {
6305 		pr_err("no right to delete : 0x%x\n", fp->daccess);
6306 		return -EACCES;
6307 	}
6308 
6309 	if (buf_len < (u64)sizeof(struct smb2_file_rename_info) +
6310 			le32_to_cpu(rename_info->FileNameLength))
6311 		return -EINVAL;
6312 
6313 	if (!le32_to_cpu(rename_info->FileNameLength))
6314 		return -EINVAL;
6315 
6316 	return smb2_rename(work, fp, rename_info, work->conn->local_nls);
6317 }
6318 
6319 static int set_file_disposition_info(struct ksmbd_file *fp,
6320 				     struct smb2_file_disposition_info *file_info)
6321 {
6322 	struct inode *inode;
6323 
6324 	if (!(fp->daccess & FILE_DELETE_LE)) {
6325 		pr_err("no right to delete : 0x%x\n", fp->daccess);
6326 		return -EACCES;
6327 	}
6328 
6329 	inode = file_inode(fp->filp);
6330 	if (file_info->DeletePending) {
6331 		if (S_ISDIR(inode->i_mode) &&
6332 		    ksmbd_vfs_empty_dir(fp) == -ENOTEMPTY)
6333 			return -EBUSY;
6334 		ksmbd_set_inode_pending_delete(fp);
6335 	} else {
6336 		ksmbd_clear_inode_pending_delete(fp);
6337 	}
6338 	return 0;
6339 }
6340 
6341 static int set_file_position_info(struct ksmbd_file *fp,
6342 				  struct smb2_file_pos_info *file_info)
6343 {
6344 	loff_t current_byte_offset;
6345 	unsigned long sector_size;
6346 	struct inode *inode;
6347 
6348 	inode = file_inode(fp->filp);
6349 	current_byte_offset = le64_to_cpu(file_info->CurrentByteOffset);
6350 	sector_size = inode->i_sb->s_blocksize;
6351 
6352 	if (current_byte_offset < 0 ||
6353 	    (fp->coption == FILE_NO_INTERMEDIATE_BUFFERING_LE &&
6354 	     current_byte_offset & (sector_size - 1))) {
6355 		pr_err("CurrentByteOffset is not valid : %llu\n",
6356 		       current_byte_offset);
6357 		return -EINVAL;
6358 	}
6359 
6360 	if (ksmbd_stream_fd(fp) == false)
6361 		fp->filp->f_pos = current_byte_offset;
6362 	else {
6363 		if (current_byte_offset > XATTR_SIZE_MAX)
6364 			current_byte_offset = XATTR_SIZE_MAX;
6365 		fp->stream.pos = current_byte_offset;
6366 	}
6367 	return 0;
6368 }
6369 
6370 static int set_file_mode_info(struct ksmbd_file *fp,
6371 			      struct smb2_file_mode_info *file_info)
6372 {
6373 	__le32 mode;
6374 
6375 	mode = file_info->Mode;
6376 
6377 	if ((mode & ~FILE_MODE_INFO_MASK)) {
6378 		pr_err("Mode is not valid : 0x%x\n", le32_to_cpu(mode));
6379 		return -EINVAL;
6380 	}
6381 
6382 	/*
6383 	 * TODO : need to implement consideration for
6384 	 * FILE_SYNCHRONOUS_IO_ALERT and FILE_SYNCHRONOUS_IO_NONALERT
6385 	 */
6386 	ksmbd_vfs_set_fadvise(fp->filp, mode);
6387 	fp->coption = mode;
6388 	return 0;
6389 }
6390 
6391 /**
6392  * smb2_set_info_file() - handler for smb2 set info command
6393  * @work:	smb work containing set info command buffer
6394  * @fp:		ksmbd_file pointer
6395  * @req:	request buffer pointer
6396  * @share:	ksmbd_share_config pointer
6397  *
6398  * Return:	0 on success, otherwise error
6399  */
6400 static int smb2_set_info_file(struct ksmbd_work *work, struct ksmbd_file *fp,
6401 			      struct smb2_set_info_req *req,
6402 			      struct ksmbd_share_config *share)
6403 {
6404 	unsigned int buf_len = le32_to_cpu(req->BufferLength);
6405 	char *buffer = (char *)req + le16_to_cpu(req->BufferOffset);
6406 
6407 	switch (req->FileInfoClass) {
6408 	case FILE_BASIC_INFORMATION:
6409 	{
6410 		if (buf_len < sizeof(struct smb2_file_basic_info))
6411 			return -EMSGSIZE;
6412 
6413 		return set_file_basic_info(fp, (struct smb2_file_basic_info *)buffer, share);
6414 	}
6415 	case FILE_ALLOCATION_INFORMATION:
6416 	{
6417 		if (buf_len < sizeof(struct smb2_file_alloc_info))
6418 			return -EMSGSIZE;
6419 
6420 		return set_file_allocation_info(work, fp,
6421 						(struct smb2_file_alloc_info *)buffer);
6422 	}
6423 	case FILE_END_OF_FILE_INFORMATION:
6424 	{
6425 		if (buf_len < sizeof(struct smb2_file_eof_info))
6426 			return -EMSGSIZE;
6427 
6428 		return set_end_of_file_info(work, fp,
6429 					    (struct smb2_file_eof_info *)buffer);
6430 	}
6431 	case FILE_RENAME_INFORMATION:
6432 	{
6433 		if (buf_len < sizeof(struct smb2_file_rename_info))
6434 			return -EMSGSIZE;
6435 
6436 		return set_rename_info(work, fp,
6437 				       (struct smb2_file_rename_info *)buffer,
6438 				       buf_len);
6439 	}
6440 	case FILE_LINK_INFORMATION:
6441 	{
6442 		if (buf_len < sizeof(struct smb2_file_link_info))
6443 			return -EMSGSIZE;
6444 
6445 		return smb2_create_link(work, work->tcon->share_conf,
6446 					(struct smb2_file_link_info *)buffer,
6447 					buf_len, fp->filp,
6448 					work->conn->local_nls);
6449 	}
6450 	case FILE_DISPOSITION_INFORMATION:
6451 	{
6452 		if (buf_len < sizeof(struct smb2_file_disposition_info))
6453 			return -EMSGSIZE;
6454 
6455 		return set_file_disposition_info(fp,
6456 						 (struct smb2_file_disposition_info *)buffer);
6457 	}
6458 	case FILE_FULL_EA_INFORMATION:
6459 	{
6460 		if (!(fp->daccess & FILE_WRITE_EA_LE)) {
6461 			pr_err("Not permitted to write ext  attr: 0x%x\n",
6462 			       fp->daccess);
6463 			return -EACCES;
6464 		}
6465 
6466 		if (buf_len < sizeof(struct smb2_ea_info))
6467 			return -EMSGSIZE;
6468 
6469 		return smb2_set_ea((struct smb2_ea_info *)buffer,
6470 				   buf_len, &fp->filp->f_path, true);
6471 	}
6472 	case FILE_POSITION_INFORMATION:
6473 	{
6474 		if (buf_len < sizeof(struct smb2_file_pos_info))
6475 			return -EMSGSIZE;
6476 
6477 		return set_file_position_info(fp, (struct smb2_file_pos_info *)buffer);
6478 	}
6479 	case FILE_MODE_INFORMATION:
6480 	{
6481 		if (buf_len < sizeof(struct smb2_file_mode_info))
6482 			return -EMSGSIZE;
6483 
6484 		return set_file_mode_info(fp, (struct smb2_file_mode_info *)buffer);
6485 	}
6486 	}
6487 
6488 	pr_err("Unimplemented Fileinfoclass :%d\n", req->FileInfoClass);
6489 	return -EOPNOTSUPP;
6490 }
6491 
6492 static int smb2_set_info_sec(struct ksmbd_file *fp, int addition_info,
6493 			     char *buffer, int buf_len)
6494 {
6495 	struct smb_ntsd *pntsd = (struct smb_ntsd *)buffer;
6496 
6497 	fp->saccess |= FILE_SHARE_DELETE_LE;
6498 
6499 	return set_info_sec(fp->conn, fp->tcon, &fp->filp->f_path, pntsd,
6500 			buf_len, false, true);
6501 }
6502 
6503 /**
6504  * smb2_set_info() - handler for smb2 set info command handler
6505  * @work:	smb work containing set info request buffer
6506  *
6507  * Return:	0 on success, otherwise error
6508  */
6509 int smb2_set_info(struct ksmbd_work *work)
6510 {
6511 	struct smb2_set_info_req *req;
6512 	struct smb2_set_info_rsp *rsp;
6513 	struct ksmbd_file *fp = NULL;
6514 	int rc = 0;
6515 	unsigned int id = KSMBD_NO_FID, pid = KSMBD_NO_FID;
6516 
6517 	ksmbd_debug(SMB, "Received smb2 set info request\n");
6518 
6519 	if (work->next_smb2_rcv_hdr_off) {
6520 		req = ksmbd_req_buf_next(work);
6521 		rsp = ksmbd_resp_buf_next(work);
6522 		if (!has_file_id(req->VolatileFileId)) {
6523 			ksmbd_debug(SMB, "Compound request set FID = %llu\n",
6524 				    work->compound_fid);
6525 			id = work->compound_fid;
6526 			pid = work->compound_pfid;
6527 		}
6528 	} else {
6529 		req = smb_get_msg(work->request_buf);
6530 		rsp = smb_get_msg(work->response_buf);
6531 	}
6532 
6533 	if (!test_tree_conn_flag(work->tcon, KSMBD_TREE_CONN_FLAG_WRITABLE)) {
6534 		ksmbd_debug(SMB, "User does not have write permission\n");
6535 		pr_err("User does not have write permission\n");
6536 		rc = -EACCES;
6537 		goto err_out;
6538 	}
6539 
6540 	if (!has_file_id(id)) {
6541 		id = req->VolatileFileId;
6542 		pid = req->PersistentFileId;
6543 	}
6544 
6545 	fp = ksmbd_lookup_fd_slow(work, id, pid);
6546 	if (!fp) {
6547 		ksmbd_debug(SMB, "Invalid id for close: %u\n", id);
6548 		rc = -ENOENT;
6549 		goto err_out;
6550 	}
6551 
6552 	switch (req->InfoType) {
6553 	case SMB2_O_INFO_FILE:
6554 		ksmbd_debug(SMB, "GOT SMB2_O_INFO_FILE\n");
6555 		rc = smb2_set_info_file(work, fp, req, work->tcon->share_conf);
6556 		break;
6557 	case SMB2_O_INFO_SECURITY:
6558 		ksmbd_debug(SMB, "GOT SMB2_O_INFO_SECURITY\n");
6559 		if (ksmbd_override_fsids(work)) {
6560 			rc = -ENOMEM;
6561 			goto err_out;
6562 		}
6563 		rc = smb2_set_info_sec(fp,
6564 				       le32_to_cpu(req->AdditionalInformation),
6565 				       (char *)req + le16_to_cpu(req->BufferOffset),
6566 				       le32_to_cpu(req->BufferLength));
6567 		ksmbd_revert_fsids(work);
6568 		break;
6569 	default:
6570 		rc = -EOPNOTSUPP;
6571 	}
6572 
6573 	if (rc < 0)
6574 		goto err_out;
6575 
6576 	rsp->StructureSize = cpu_to_le16(2);
6577 	rc = ksmbd_iov_pin_rsp(work, (void *)rsp,
6578 			       sizeof(struct smb2_set_info_rsp));
6579 	if (rc)
6580 		goto err_out;
6581 	ksmbd_fd_put(work, fp);
6582 	return 0;
6583 
6584 err_out:
6585 	if (rc == -EACCES || rc == -EPERM || rc == -EXDEV)
6586 		rsp->hdr.Status = STATUS_ACCESS_DENIED;
6587 	else if (rc == -EINVAL)
6588 		rsp->hdr.Status = STATUS_INVALID_PARAMETER;
6589 	else if (rc == -EMSGSIZE)
6590 		rsp->hdr.Status = STATUS_INFO_LENGTH_MISMATCH;
6591 	else if (rc == -ESHARE)
6592 		rsp->hdr.Status = STATUS_SHARING_VIOLATION;
6593 	else if (rc == -ENOENT)
6594 		rsp->hdr.Status = STATUS_OBJECT_NAME_INVALID;
6595 	else if (rc == -EBUSY || rc == -ENOTEMPTY)
6596 		rsp->hdr.Status = STATUS_DIRECTORY_NOT_EMPTY;
6597 	else if (rc == -EAGAIN)
6598 		rsp->hdr.Status = STATUS_FILE_LOCK_CONFLICT;
6599 	else if (rc == -EBADF || rc == -ESTALE)
6600 		rsp->hdr.Status = STATUS_INVALID_HANDLE;
6601 	else if (rc == -EEXIST)
6602 		rsp->hdr.Status = STATUS_OBJECT_NAME_COLLISION;
6603 	else if (rsp->hdr.Status == 0 || rc == -EOPNOTSUPP)
6604 		rsp->hdr.Status = STATUS_INVALID_INFO_CLASS;
6605 	smb2_set_err_rsp(work);
6606 	ksmbd_fd_put(work, fp);
6607 	ksmbd_debug(SMB, "error while processing smb2 query rc = %d\n", rc);
6608 	return rc;
6609 }
6610 
6611 /**
6612  * smb2_read_pipe() - handler for smb2 read from IPC pipe
6613  * @work:	smb work containing read IPC pipe command buffer
6614  *
6615  * Return:	0 on success, otherwise error
6616  */
6617 static noinline int smb2_read_pipe(struct ksmbd_work *work)
6618 {
6619 	int nbytes = 0, err;
6620 	u64 id;
6621 	struct ksmbd_rpc_command *rpc_resp;
6622 	struct smb2_read_req *req;
6623 	struct smb2_read_rsp *rsp;
6624 
6625 	WORK_BUFFERS(work, req, rsp);
6626 
6627 	id = req->VolatileFileId;
6628 
6629 	rpc_resp = ksmbd_rpc_read(work->sess, id);
6630 	if (rpc_resp) {
6631 		void *aux_payload_buf;
6632 
6633 		if (rpc_resp->flags != KSMBD_RPC_OK) {
6634 			err = -EINVAL;
6635 			goto out;
6636 		}
6637 
6638 		aux_payload_buf =
6639 			kvmalloc(rpc_resp->payload_sz, KSMBD_DEFAULT_GFP);
6640 		if (!aux_payload_buf) {
6641 			err = -ENOMEM;
6642 			goto out;
6643 		}
6644 
6645 		memcpy(aux_payload_buf, rpc_resp->payload, rpc_resp->payload_sz);
6646 
6647 		nbytes = rpc_resp->payload_sz;
6648 		err = ksmbd_iov_pin_rsp_read(work, (void *)rsp,
6649 					     offsetof(struct smb2_read_rsp, Buffer),
6650 					     aux_payload_buf, nbytes);
6651 		if (err) {
6652 			kvfree(aux_payload_buf);
6653 			goto out;
6654 		}
6655 		kvfree(rpc_resp);
6656 	} else {
6657 		err = ksmbd_iov_pin_rsp(work, (void *)rsp,
6658 					offsetof(struct smb2_read_rsp, Buffer));
6659 		if (err)
6660 			goto out;
6661 	}
6662 
6663 	rsp->StructureSize = cpu_to_le16(17);
6664 	rsp->DataOffset = 80;
6665 	rsp->Reserved = 0;
6666 	rsp->DataLength = cpu_to_le32(nbytes);
6667 	rsp->DataRemaining = 0;
6668 	rsp->Flags = 0;
6669 	return 0;
6670 
6671 out:
6672 	rsp->hdr.Status = STATUS_UNEXPECTED_IO_ERROR;
6673 	smb2_set_err_rsp(work);
6674 	kvfree(rpc_resp);
6675 	return err;
6676 }
6677 
6678 static int smb2_set_remote_key_for_rdma(struct ksmbd_work *work,
6679 					struct smbdirect_buffer_descriptor_v1 *desc,
6680 					__le32 Channel,
6681 					__le16 ChannelInfoLength)
6682 {
6683 	unsigned int i, ch_count;
6684 
6685 	if (work->conn->dialect == SMB30_PROT_ID &&
6686 	    Channel != SMB2_CHANNEL_RDMA_V1)
6687 		return -EINVAL;
6688 
6689 	ch_count = le16_to_cpu(ChannelInfoLength) / sizeof(*desc);
6690 	if (ksmbd_debug_types & KSMBD_DEBUG_RDMA) {
6691 		for (i = 0; i < ch_count; i++) {
6692 			pr_info("RDMA r/w request %#x: token %#x, length %#x\n",
6693 				i,
6694 				le32_to_cpu(desc[i].token),
6695 				le32_to_cpu(desc[i].length));
6696 		}
6697 	}
6698 	if (!ch_count)
6699 		return -EINVAL;
6700 
6701 	work->need_invalidate_rkey =
6702 		(Channel == SMB2_CHANNEL_RDMA_V1_INVALIDATE);
6703 	if (Channel == SMB2_CHANNEL_RDMA_V1_INVALIDATE)
6704 		work->remote_key = le32_to_cpu(desc->token);
6705 	return 0;
6706 }
6707 
6708 static ssize_t smb2_read_rdma_channel(struct ksmbd_work *work,
6709 				      struct smb2_read_req *req, void *data_buf,
6710 				      size_t length)
6711 {
6712 	int err;
6713 
6714 	err = ksmbd_conn_rdma_write(work->conn, data_buf, length,
6715 				    (struct smbdirect_buffer_descriptor_v1 *)
6716 				    ((char *)req + le16_to_cpu(req->ReadChannelInfoOffset)),
6717 				    le16_to_cpu(req->ReadChannelInfoLength));
6718 	if (err)
6719 		return err;
6720 
6721 	return length;
6722 }
6723 
6724 /**
6725  * smb2_read() - handler for smb2 read from file
6726  * @work:	smb work containing read command buffer
6727  *
6728  * Return:	0 on success, otherwise error
6729  */
6730 int smb2_read(struct ksmbd_work *work)
6731 {
6732 	struct ksmbd_conn *conn = work->conn;
6733 	struct smb2_read_req *req;
6734 	struct smb2_read_rsp *rsp;
6735 	struct ksmbd_file *fp = NULL;
6736 	loff_t offset;
6737 	size_t length, mincount;
6738 	ssize_t nbytes = 0, remain_bytes = 0;
6739 	int err = 0;
6740 	bool is_rdma_channel = false;
6741 	unsigned int max_read_size = conn->vals->max_read_size;
6742 	unsigned int id = KSMBD_NO_FID, pid = KSMBD_NO_FID;
6743 	void *aux_payload_buf;
6744 
6745 	ksmbd_debug(SMB, "Received smb2 read request\n");
6746 
6747 	if (test_share_config_flag(work->tcon->share_conf,
6748 				   KSMBD_SHARE_FLAG_PIPE)) {
6749 		ksmbd_debug(SMB, "IPC pipe read request\n");
6750 		return smb2_read_pipe(work);
6751 	}
6752 
6753 	if (work->next_smb2_rcv_hdr_off) {
6754 		req = ksmbd_req_buf_next(work);
6755 		rsp = ksmbd_resp_buf_next(work);
6756 		if (!has_file_id(req->VolatileFileId)) {
6757 			ksmbd_debug(SMB, "Compound request set FID = %llu\n",
6758 					work->compound_fid);
6759 			id = work->compound_fid;
6760 			pid = work->compound_pfid;
6761 		}
6762 	} else {
6763 		req = smb_get_msg(work->request_buf);
6764 		rsp = smb_get_msg(work->response_buf);
6765 	}
6766 
6767 	if (!has_file_id(id)) {
6768 		id = req->VolatileFileId;
6769 		pid = req->PersistentFileId;
6770 	}
6771 
6772 	if (req->Channel == SMB2_CHANNEL_RDMA_V1_INVALIDATE ||
6773 	    req->Channel == SMB2_CHANNEL_RDMA_V1) {
6774 		is_rdma_channel = true;
6775 		max_read_size = get_smbd_max_read_write_size(work->conn->transport);
6776 		if (max_read_size == 0) {
6777 			err = -EINVAL;
6778 			goto out;
6779 		}
6780 	}
6781 
6782 	if (is_rdma_channel == true) {
6783 		unsigned int ch_offset = le16_to_cpu(req->ReadChannelInfoOffset);
6784 
6785 		if (ch_offset < offsetof(struct smb2_read_req, Buffer)) {
6786 			err = -EINVAL;
6787 			goto out;
6788 		}
6789 		err = smb2_set_remote_key_for_rdma(work,
6790 						   (struct smbdirect_buffer_descriptor_v1 *)
6791 						   ((char *)req + ch_offset),
6792 						   req->Channel,
6793 						   req->ReadChannelInfoLength);
6794 		if (err)
6795 			goto out;
6796 	}
6797 
6798 	fp = ksmbd_lookup_fd_slow(work, id, pid);
6799 	if (!fp) {
6800 		err = -ENOENT;
6801 		goto out;
6802 	}
6803 
6804 	if (!(fp->daccess & (FILE_READ_DATA_LE | FILE_READ_ATTRIBUTES_LE))) {
6805 		pr_err("Not permitted to read : 0x%x\n", fp->daccess);
6806 		err = -EACCES;
6807 		goto out;
6808 	}
6809 
6810 	offset = le64_to_cpu(req->Offset);
6811 	if (offset < 0) {
6812 		err = -EINVAL;
6813 		goto out;
6814 	}
6815 	length = le32_to_cpu(req->Length);
6816 	mincount = le32_to_cpu(req->MinimumCount);
6817 
6818 	if (length > max_read_size) {
6819 		ksmbd_debug(SMB, "limiting read size to max size(%u)\n",
6820 			    max_read_size);
6821 		err = -EINVAL;
6822 		goto out;
6823 	}
6824 
6825 	ksmbd_debug(SMB, "filename %pD, offset %lld, len %zu\n",
6826 		    fp->filp, offset, length);
6827 
6828 	aux_payload_buf = kvzalloc(ALIGN(length, 8), KSMBD_DEFAULT_GFP);
6829 	if (!aux_payload_buf) {
6830 		err = -ENOMEM;
6831 		goto out;
6832 	}
6833 
6834 	nbytes = ksmbd_vfs_read(work, fp, length, &offset, aux_payload_buf);
6835 	if (nbytes < 0) {
6836 		kvfree(aux_payload_buf);
6837 		err = nbytes;
6838 		goto out;
6839 	}
6840 
6841 	if ((nbytes == 0 && length != 0) || nbytes < mincount) {
6842 		kvfree(aux_payload_buf);
6843 		rsp->hdr.Status = STATUS_END_OF_FILE;
6844 		smb2_set_err_rsp(work);
6845 		ksmbd_fd_put(work, fp);
6846 		return -ENODATA;
6847 	}
6848 
6849 	ksmbd_debug(SMB, "nbytes %zu, offset %lld mincount %zu\n",
6850 		    nbytes, offset, mincount);
6851 
6852 	if (is_rdma_channel == true) {
6853 		/* write data to the client using rdma channel */
6854 		remain_bytes = smb2_read_rdma_channel(work, req,
6855 						      aux_payload_buf,
6856 						      nbytes);
6857 		kvfree(aux_payload_buf);
6858 		aux_payload_buf = NULL;
6859 		nbytes = 0;
6860 		if (remain_bytes < 0) {
6861 			err = (int)remain_bytes;
6862 			goto out;
6863 		}
6864 	}
6865 
6866 	rsp->StructureSize = cpu_to_le16(17);
6867 	rsp->DataOffset = 80;
6868 	rsp->Reserved = 0;
6869 	rsp->DataLength = cpu_to_le32(nbytes);
6870 	rsp->DataRemaining = cpu_to_le32(remain_bytes);
6871 	rsp->Flags = 0;
6872 	err = ksmbd_iov_pin_rsp_read(work, (void *)rsp,
6873 				     offsetof(struct smb2_read_rsp, Buffer),
6874 				     aux_payload_buf, nbytes);
6875 	if (err) {
6876 		kvfree(aux_payload_buf);
6877 		goto out;
6878 	}
6879 	ksmbd_fd_put(work, fp);
6880 	return 0;
6881 
6882 out:
6883 	if (err) {
6884 		if (err == -EISDIR)
6885 			rsp->hdr.Status = STATUS_INVALID_DEVICE_REQUEST;
6886 		else if (err == -EAGAIN)
6887 			rsp->hdr.Status = STATUS_FILE_LOCK_CONFLICT;
6888 		else if (err == -ENOENT)
6889 			rsp->hdr.Status = STATUS_FILE_CLOSED;
6890 		else if (err == -EACCES)
6891 			rsp->hdr.Status = STATUS_ACCESS_DENIED;
6892 		else if (err == -ESHARE)
6893 			rsp->hdr.Status = STATUS_SHARING_VIOLATION;
6894 		else if (err == -EINVAL)
6895 			rsp->hdr.Status = STATUS_INVALID_PARAMETER;
6896 		else
6897 			rsp->hdr.Status = STATUS_INVALID_HANDLE;
6898 
6899 		smb2_set_err_rsp(work);
6900 	}
6901 	ksmbd_fd_put(work, fp);
6902 	return err;
6903 }
6904 
6905 /**
6906  * smb2_write_pipe() - handler for smb2 write on IPC pipe
6907  * @work:	smb work containing write IPC pipe command buffer
6908  *
6909  * Return:	0 on success, otherwise error
6910  */
6911 static noinline int smb2_write_pipe(struct ksmbd_work *work)
6912 {
6913 	struct smb2_write_req *req;
6914 	struct smb2_write_rsp *rsp;
6915 	struct ksmbd_rpc_command *rpc_resp;
6916 	u64 id = 0;
6917 	int err = 0, ret = 0;
6918 	char *data_buf;
6919 	size_t length;
6920 
6921 	WORK_BUFFERS(work, req, rsp);
6922 
6923 	length = le32_to_cpu(req->Length);
6924 	id = req->VolatileFileId;
6925 
6926 	if ((u64)le16_to_cpu(req->DataOffset) + length >
6927 	    get_rfc1002_len(work->request_buf)) {
6928 		pr_err("invalid write data offset %u, smb_len %u\n",
6929 		       le16_to_cpu(req->DataOffset),
6930 		       get_rfc1002_len(work->request_buf));
6931 		err = -EINVAL;
6932 		goto out;
6933 	}
6934 
6935 	data_buf = (char *)(((char *)&req->hdr.ProtocolId) +
6936 			   le16_to_cpu(req->DataOffset));
6937 
6938 	rpc_resp = ksmbd_rpc_write(work->sess, id, data_buf, length);
6939 	if (rpc_resp) {
6940 		if (rpc_resp->flags == KSMBD_RPC_ENOTIMPLEMENTED) {
6941 			rsp->hdr.Status = STATUS_NOT_SUPPORTED;
6942 			kvfree(rpc_resp);
6943 			smb2_set_err_rsp(work);
6944 			return -EOPNOTSUPP;
6945 		}
6946 		if (rpc_resp->flags != KSMBD_RPC_OK) {
6947 			rsp->hdr.Status = STATUS_INVALID_HANDLE;
6948 			smb2_set_err_rsp(work);
6949 			kvfree(rpc_resp);
6950 			return ret;
6951 		}
6952 		kvfree(rpc_resp);
6953 	}
6954 
6955 	rsp->StructureSize = cpu_to_le16(17);
6956 	rsp->DataOffset = 0;
6957 	rsp->Reserved = 0;
6958 	rsp->DataLength = cpu_to_le32(length);
6959 	rsp->DataRemaining = 0;
6960 	rsp->Reserved2 = 0;
6961 	err = ksmbd_iov_pin_rsp(work, (void *)rsp,
6962 				offsetof(struct smb2_write_rsp, Buffer));
6963 out:
6964 	if (err) {
6965 		rsp->hdr.Status = STATUS_INVALID_HANDLE;
6966 		smb2_set_err_rsp(work);
6967 	}
6968 
6969 	return err;
6970 }
6971 
6972 static ssize_t smb2_write_rdma_channel(struct ksmbd_work *work,
6973 				       struct smb2_write_req *req,
6974 				       struct ksmbd_file *fp,
6975 				       loff_t offset, size_t length, bool sync)
6976 {
6977 	char *data_buf;
6978 	int ret;
6979 	ssize_t nbytes;
6980 
6981 	data_buf = kvzalloc(length, KSMBD_DEFAULT_GFP);
6982 	if (!data_buf)
6983 		return -ENOMEM;
6984 
6985 	ret = ksmbd_conn_rdma_read(work->conn, data_buf, length,
6986 				   (struct smbdirect_buffer_descriptor_v1 *)
6987 				   ((char *)req + le16_to_cpu(req->WriteChannelInfoOffset)),
6988 				   le16_to_cpu(req->WriteChannelInfoLength));
6989 	if (ret < 0) {
6990 		kvfree(data_buf);
6991 		return ret;
6992 	}
6993 
6994 	ret = ksmbd_vfs_write(work, fp, data_buf, length, &offset, sync, &nbytes);
6995 	kvfree(data_buf);
6996 	if (ret < 0)
6997 		return ret;
6998 
6999 	return nbytes;
7000 }
7001 
7002 /**
7003  * smb2_write() - handler for smb2 write from file
7004  * @work:	smb work containing write command buffer
7005  *
7006  * Return:	0 on success, otherwise error
7007  */
7008 int smb2_write(struct ksmbd_work *work)
7009 {
7010 	struct smb2_write_req *req;
7011 	struct smb2_write_rsp *rsp;
7012 	struct ksmbd_file *fp = NULL;
7013 	loff_t offset;
7014 	size_t length;
7015 	ssize_t nbytes;
7016 	char *data_buf;
7017 	bool writethrough = false, is_rdma_channel = false;
7018 	int err = 0;
7019 	unsigned int max_write_size = work->conn->vals->max_write_size;
7020 
7021 	ksmbd_debug(SMB, "Received smb2 write request\n");
7022 
7023 	WORK_BUFFERS(work, req, rsp);
7024 
7025 	if (test_share_config_flag(work->tcon->share_conf, KSMBD_SHARE_FLAG_PIPE)) {
7026 		ksmbd_debug(SMB, "IPC pipe write request\n");
7027 		return smb2_write_pipe(work);
7028 	}
7029 
7030 	offset = le64_to_cpu(req->Offset);
7031 	if (offset < 0)
7032 		return -EINVAL;
7033 	length = le32_to_cpu(req->Length);
7034 
7035 	if (req->Channel == SMB2_CHANNEL_RDMA_V1 ||
7036 	    req->Channel == SMB2_CHANNEL_RDMA_V1_INVALIDATE) {
7037 		is_rdma_channel = true;
7038 		max_write_size = get_smbd_max_read_write_size(work->conn->transport);
7039 		if (max_write_size == 0) {
7040 			err = -EINVAL;
7041 			goto out;
7042 		}
7043 		length = le32_to_cpu(req->RemainingBytes);
7044 	}
7045 
7046 	if (is_rdma_channel == true) {
7047 		unsigned int ch_offset = le16_to_cpu(req->WriteChannelInfoOffset);
7048 
7049 		if (req->Length != 0 || req->DataOffset != 0 ||
7050 		    ch_offset < offsetof(struct smb2_write_req, Buffer)) {
7051 			err = -EINVAL;
7052 			goto out;
7053 		}
7054 		err = smb2_set_remote_key_for_rdma(work,
7055 						   (struct smbdirect_buffer_descriptor_v1 *)
7056 						   ((char *)req + ch_offset),
7057 						   req->Channel,
7058 						   req->WriteChannelInfoLength);
7059 		if (err)
7060 			goto out;
7061 	}
7062 
7063 	if (!test_tree_conn_flag(work->tcon, KSMBD_TREE_CONN_FLAG_WRITABLE)) {
7064 		ksmbd_debug(SMB, "User does not have write permission\n");
7065 		err = -EACCES;
7066 		goto out;
7067 	}
7068 
7069 	fp = ksmbd_lookup_fd_slow(work, req->VolatileFileId, req->PersistentFileId);
7070 	if (!fp) {
7071 		err = -ENOENT;
7072 		goto out;
7073 	}
7074 
7075 	if (!(fp->daccess & (FILE_WRITE_DATA_LE | FILE_READ_ATTRIBUTES_LE))) {
7076 		pr_err("Not permitted to write : 0x%x\n", fp->daccess);
7077 		err = -EACCES;
7078 		goto out;
7079 	}
7080 
7081 	if (length > max_write_size) {
7082 		ksmbd_debug(SMB, "limiting write size to max size(%u)\n",
7083 			    max_write_size);
7084 		err = -EINVAL;
7085 		goto out;
7086 	}
7087 
7088 	ksmbd_debug(SMB, "flags %u\n", le32_to_cpu(req->Flags));
7089 	if (le32_to_cpu(req->Flags) & SMB2_WRITEFLAG_WRITE_THROUGH)
7090 		writethrough = true;
7091 
7092 	if (is_rdma_channel == false) {
7093 		if (le16_to_cpu(req->DataOffset) <
7094 		    offsetof(struct smb2_write_req, Buffer)) {
7095 			err = -EINVAL;
7096 			goto out;
7097 		}
7098 
7099 		data_buf = (char *)(((char *)&req->hdr.ProtocolId) +
7100 				    le16_to_cpu(req->DataOffset));
7101 
7102 		ksmbd_debug(SMB, "filename %pD, offset %lld, len %zu\n",
7103 			    fp->filp, offset, length);
7104 		err = ksmbd_vfs_write(work, fp, data_buf, length, &offset,
7105 				      writethrough, &nbytes);
7106 		if (err < 0)
7107 			goto out;
7108 	} else {
7109 		/* read data from the client using rdma channel, and
7110 		 * write the data.
7111 		 */
7112 		nbytes = smb2_write_rdma_channel(work, req, fp, offset, length,
7113 						 writethrough);
7114 		if (nbytes < 0) {
7115 			err = (int)nbytes;
7116 			goto out;
7117 		}
7118 	}
7119 
7120 	rsp->StructureSize = cpu_to_le16(17);
7121 	rsp->DataOffset = 0;
7122 	rsp->Reserved = 0;
7123 	rsp->DataLength = cpu_to_le32(nbytes);
7124 	rsp->DataRemaining = 0;
7125 	rsp->Reserved2 = 0;
7126 	err = ksmbd_iov_pin_rsp(work, rsp, offsetof(struct smb2_write_rsp, Buffer));
7127 	if (err)
7128 		goto out;
7129 	ksmbd_fd_put(work, fp);
7130 	return 0;
7131 
7132 out:
7133 	if (err == -EAGAIN)
7134 		rsp->hdr.Status = STATUS_FILE_LOCK_CONFLICT;
7135 	else if (err == -ENOSPC || err == -EFBIG)
7136 		rsp->hdr.Status = STATUS_DISK_FULL;
7137 	else if (err == -ENOENT)
7138 		rsp->hdr.Status = STATUS_FILE_CLOSED;
7139 	else if (err == -EACCES)
7140 		rsp->hdr.Status = STATUS_ACCESS_DENIED;
7141 	else if (err == -ESHARE)
7142 		rsp->hdr.Status = STATUS_SHARING_VIOLATION;
7143 	else if (err == -EINVAL)
7144 		rsp->hdr.Status = STATUS_INVALID_PARAMETER;
7145 	else
7146 		rsp->hdr.Status = STATUS_INVALID_HANDLE;
7147 
7148 	smb2_set_err_rsp(work);
7149 	ksmbd_fd_put(work, fp);
7150 	return err;
7151 }
7152 
7153 /**
7154  * smb2_flush() - handler for smb2 flush file - fsync
7155  * @work:	smb work containing flush command buffer
7156  *
7157  * Return:	0 on success, otherwise error
7158  */
7159 int smb2_flush(struct ksmbd_work *work)
7160 {
7161 	struct smb2_flush_req *req;
7162 	struct smb2_flush_rsp *rsp;
7163 	int err;
7164 
7165 	WORK_BUFFERS(work, req, rsp);
7166 
7167 	ksmbd_debug(SMB, "Received smb2 flush request(fid : %llu)\n", req->VolatileFileId);
7168 
7169 	err = ksmbd_vfs_fsync(work, req->VolatileFileId, req->PersistentFileId);
7170 	if (err)
7171 		goto out;
7172 
7173 	rsp->StructureSize = cpu_to_le16(4);
7174 	rsp->Reserved = 0;
7175 	return ksmbd_iov_pin_rsp(work, rsp, sizeof(struct smb2_flush_rsp));
7176 
7177 out:
7178 	rsp->hdr.Status = STATUS_INVALID_HANDLE;
7179 	smb2_set_err_rsp(work);
7180 	return err;
7181 }
7182 
7183 /**
7184  * smb2_cancel() - handler for smb2 cancel command
7185  * @work:	smb work containing cancel command buffer
7186  *
7187  * Return:	0 on success, otherwise error
7188  */
7189 int smb2_cancel(struct ksmbd_work *work)
7190 {
7191 	struct ksmbd_conn *conn = work->conn;
7192 	struct smb2_hdr *hdr = smb_get_msg(work->request_buf);
7193 	struct smb2_hdr *chdr;
7194 	struct ksmbd_work *iter;
7195 	struct list_head *command_list;
7196 
7197 	if (work->next_smb2_rcv_hdr_off)
7198 		hdr = ksmbd_resp_buf_next(work);
7199 
7200 	ksmbd_debug(SMB, "smb2 cancel called on mid %llu, async flags 0x%x\n",
7201 		    hdr->MessageId, hdr->Flags);
7202 
7203 	if (hdr->Flags & SMB2_FLAGS_ASYNC_COMMAND) {
7204 		command_list = &conn->async_requests;
7205 
7206 		spin_lock(&conn->request_lock);
7207 		list_for_each_entry(iter, command_list,
7208 				    async_request_entry) {
7209 			chdr = smb_get_msg(iter->request_buf);
7210 
7211 			if (iter->async_id !=
7212 			    le64_to_cpu(hdr->Id.AsyncId))
7213 				continue;
7214 
7215 			ksmbd_debug(SMB,
7216 				    "smb2 with AsyncId %llu cancelled command = 0x%x\n",
7217 				    le64_to_cpu(hdr->Id.AsyncId),
7218 				    le16_to_cpu(chdr->Command));
7219 			iter->state = KSMBD_WORK_CANCELLED;
7220 			if (iter->cancel_fn)
7221 				iter->cancel_fn(iter->cancel_argv);
7222 			break;
7223 		}
7224 		spin_unlock(&conn->request_lock);
7225 	} else {
7226 		command_list = &conn->requests;
7227 
7228 		spin_lock(&conn->request_lock);
7229 		list_for_each_entry(iter, command_list, request_entry) {
7230 			chdr = smb_get_msg(iter->request_buf);
7231 
7232 			if (chdr->MessageId != hdr->MessageId ||
7233 			    iter == work)
7234 				continue;
7235 
7236 			ksmbd_debug(SMB,
7237 				    "smb2 with mid %llu cancelled command = 0x%x\n",
7238 				    le64_to_cpu(hdr->MessageId),
7239 				    le16_to_cpu(chdr->Command));
7240 			iter->state = KSMBD_WORK_CANCELLED;
7241 			break;
7242 		}
7243 		spin_unlock(&conn->request_lock);
7244 	}
7245 
7246 	/* For SMB2_CANCEL command itself send no response*/
7247 	work->send_no_response = 1;
7248 	return 0;
7249 }
7250 
7251 struct file_lock *smb_flock_init(struct file *f)
7252 {
7253 	struct file_lock *fl;
7254 
7255 	fl = locks_alloc_lock();
7256 	if (!fl)
7257 		goto out;
7258 
7259 	locks_init_lock(fl);
7260 
7261 	fl->c.flc_owner = f;
7262 	fl->c.flc_pid = current->tgid;
7263 	fl->c.flc_file = f;
7264 	fl->c.flc_flags = FL_POSIX;
7265 	fl->fl_ops = NULL;
7266 	fl->fl_lmops = NULL;
7267 
7268 out:
7269 	return fl;
7270 }
7271 
7272 static int smb2_set_flock_flags(struct file_lock *flock, int flags)
7273 {
7274 	int cmd = -EINVAL;
7275 
7276 	/* Checking for wrong flag combination during lock request*/
7277 	switch (flags) {
7278 	case SMB2_LOCKFLAG_SHARED:
7279 		ksmbd_debug(SMB, "received shared request\n");
7280 		cmd = F_SETLKW;
7281 		flock->c.flc_type = F_RDLCK;
7282 		flock->c.flc_flags |= FL_SLEEP;
7283 		break;
7284 	case SMB2_LOCKFLAG_EXCLUSIVE:
7285 		ksmbd_debug(SMB, "received exclusive request\n");
7286 		cmd = F_SETLKW;
7287 		flock->c.flc_type = F_WRLCK;
7288 		flock->c.flc_flags |= FL_SLEEP;
7289 		break;
7290 	case SMB2_LOCKFLAG_SHARED | SMB2_LOCKFLAG_FAIL_IMMEDIATELY:
7291 		ksmbd_debug(SMB,
7292 			    "received shared & fail immediately request\n");
7293 		cmd = F_SETLK;
7294 		flock->c.flc_type = F_RDLCK;
7295 		break;
7296 	case SMB2_LOCKFLAG_EXCLUSIVE | SMB2_LOCKFLAG_FAIL_IMMEDIATELY:
7297 		ksmbd_debug(SMB,
7298 			    "received exclusive & fail immediately request\n");
7299 		cmd = F_SETLK;
7300 		flock->c.flc_type = F_WRLCK;
7301 		break;
7302 	case SMB2_LOCKFLAG_UNLOCK:
7303 		ksmbd_debug(SMB, "received unlock request\n");
7304 		flock->c.flc_type = F_UNLCK;
7305 		cmd = F_SETLK;
7306 		break;
7307 	}
7308 
7309 	return cmd;
7310 }
7311 
7312 static struct ksmbd_lock *smb2_lock_init(struct file_lock *flock,
7313 					 unsigned int cmd, int flags,
7314 					 struct list_head *lock_list)
7315 {
7316 	struct ksmbd_lock *lock;
7317 
7318 	lock = kzalloc(sizeof(struct ksmbd_lock), KSMBD_DEFAULT_GFP);
7319 	if (!lock)
7320 		return NULL;
7321 
7322 	lock->cmd = cmd;
7323 	lock->fl = flock;
7324 	lock->start = flock->fl_start;
7325 	lock->end = flock->fl_end;
7326 	lock->flags = flags;
7327 	if (lock->start == lock->end)
7328 		lock->zero_len = 1;
7329 	INIT_LIST_HEAD(&lock->clist);
7330 	INIT_LIST_HEAD(&lock->flist);
7331 	INIT_LIST_HEAD(&lock->llist);
7332 	list_add_tail(&lock->llist, lock_list);
7333 
7334 	return lock;
7335 }
7336 
7337 static void smb2_remove_blocked_lock(void **argv)
7338 {
7339 	struct file_lock *flock = (struct file_lock *)argv[0];
7340 
7341 	ksmbd_vfs_posix_lock_unblock(flock);
7342 	locks_wake_up(flock);
7343 }
7344 
7345 static inline bool lock_defer_pending(struct file_lock *fl)
7346 {
7347 	/* check pending lock waiters */
7348 	return waitqueue_active(&fl->c.flc_wait);
7349 }
7350 
7351 /**
7352  * smb2_lock() - handler for smb2 file lock command
7353  * @work:	smb work containing lock command buffer
7354  *
7355  * Return:	0 on success, otherwise error
7356  */
7357 int smb2_lock(struct ksmbd_work *work)
7358 {
7359 	struct smb2_lock_req *req;
7360 	struct smb2_lock_rsp *rsp;
7361 	struct smb2_lock_element *lock_ele;
7362 	struct ksmbd_file *fp = NULL;
7363 	struct file_lock *flock = NULL;
7364 	struct file *filp = NULL;
7365 	int lock_count;
7366 	int flags = 0;
7367 	int cmd = 0;
7368 	int err = -EIO, i, rc = 0;
7369 	u64 lock_start, lock_length;
7370 	struct ksmbd_lock *smb_lock = NULL, *cmp_lock, *tmp, *tmp2;
7371 	struct ksmbd_conn *conn;
7372 	int nolock = 0;
7373 	LIST_HEAD(lock_list);
7374 	LIST_HEAD(rollback_list);
7375 	int prior_lock = 0, bkt;
7376 
7377 	WORK_BUFFERS(work, req, rsp);
7378 
7379 	ksmbd_debug(SMB, "Received smb2 lock request\n");
7380 	fp = ksmbd_lookup_fd_slow(work, req->VolatileFileId, req->PersistentFileId);
7381 	if (!fp) {
7382 		ksmbd_debug(SMB, "Invalid file id for lock : %llu\n", req->VolatileFileId);
7383 		err = -ENOENT;
7384 		goto out2;
7385 	}
7386 
7387 	filp = fp->filp;
7388 	lock_count = le16_to_cpu(req->LockCount);
7389 	lock_ele = req->locks;
7390 
7391 	ksmbd_debug(SMB, "lock count is %d\n", lock_count);
7392 	if (!lock_count) {
7393 		err = -EINVAL;
7394 		goto out2;
7395 	}
7396 
7397 	for (i = 0; i < lock_count; i++) {
7398 		flags = le32_to_cpu(lock_ele[i].Flags);
7399 
7400 		flock = smb_flock_init(filp);
7401 		if (!flock)
7402 			goto out;
7403 
7404 		cmd = smb2_set_flock_flags(flock, flags);
7405 
7406 		lock_start = le64_to_cpu(lock_ele[i].Offset);
7407 		lock_length = le64_to_cpu(lock_ele[i].Length);
7408 		if (lock_start > U64_MAX - lock_length) {
7409 			pr_err("Invalid lock range requested\n");
7410 			rsp->hdr.Status = STATUS_INVALID_LOCK_RANGE;
7411 			locks_free_lock(flock);
7412 			goto out;
7413 		}
7414 
7415 		if (lock_start > OFFSET_MAX)
7416 			flock->fl_start = OFFSET_MAX;
7417 		else
7418 			flock->fl_start = lock_start;
7419 
7420 		lock_length = le64_to_cpu(lock_ele[i].Length);
7421 		if (lock_length > OFFSET_MAX - flock->fl_start)
7422 			lock_length = OFFSET_MAX - flock->fl_start;
7423 
7424 		flock->fl_end = flock->fl_start + lock_length;
7425 
7426 		if (flock->fl_end < flock->fl_start) {
7427 			ksmbd_debug(SMB,
7428 				    "the end offset(%llx) is smaller than the start offset(%llx)\n",
7429 				    flock->fl_end, flock->fl_start);
7430 			rsp->hdr.Status = STATUS_INVALID_LOCK_RANGE;
7431 			locks_free_lock(flock);
7432 			goto out;
7433 		}
7434 
7435 		/* Check conflict locks in one request */
7436 		list_for_each_entry(cmp_lock, &lock_list, llist) {
7437 			if (cmp_lock->fl->fl_start <= flock->fl_start &&
7438 			    cmp_lock->fl->fl_end >= flock->fl_end) {
7439 				if (cmp_lock->fl->c.flc_type != F_UNLCK &&
7440 				    flock->c.flc_type != F_UNLCK) {
7441 					pr_err("conflict two locks in one request\n");
7442 					err = -EINVAL;
7443 					locks_free_lock(flock);
7444 					goto out;
7445 				}
7446 			}
7447 		}
7448 
7449 		smb_lock = smb2_lock_init(flock, cmd, flags, &lock_list);
7450 		if (!smb_lock) {
7451 			err = -EINVAL;
7452 			locks_free_lock(flock);
7453 			goto out;
7454 		}
7455 	}
7456 
7457 	list_for_each_entry_safe(smb_lock, tmp, &lock_list, llist) {
7458 		if (smb_lock->cmd < 0) {
7459 			err = -EINVAL;
7460 			goto out;
7461 		}
7462 
7463 		if (!(smb_lock->flags & SMB2_LOCKFLAG_MASK)) {
7464 			err = -EINVAL;
7465 			goto out;
7466 		}
7467 
7468 		if ((prior_lock & (SMB2_LOCKFLAG_EXCLUSIVE | SMB2_LOCKFLAG_SHARED) &&
7469 		     smb_lock->flags & SMB2_LOCKFLAG_UNLOCK) ||
7470 		    (prior_lock == SMB2_LOCKFLAG_UNLOCK &&
7471 		     !(smb_lock->flags & SMB2_LOCKFLAG_UNLOCK))) {
7472 			err = -EINVAL;
7473 			goto out;
7474 		}
7475 
7476 		prior_lock = smb_lock->flags;
7477 
7478 		if (!(smb_lock->flags & SMB2_LOCKFLAG_UNLOCK) &&
7479 		    !(smb_lock->flags & SMB2_LOCKFLAG_FAIL_IMMEDIATELY))
7480 			goto no_check_cl;
7481 
7482 		nolock = 1;
7483 		/* check locks in connection list */
7484 		down_read(&conn_list_lock);
7485 		hash_for_each(conn_list, bkt, conn, hlist) {
7486 			spin_lock(&conn->llist_lock);
7487 			list_for_each_entry_safe(cmp_lock, tmp2, &conn->lock_list, clist) {
7488 				if (file_inode(cmp_lock->fl->c.flc_file) !=
7489 				    file_inode(smb_lock->fl->c.flc_file))
7490 					continue;
7491 
7492 				if (lock_is_unlock(smb_lock->fl)) {
7493 					if (cmp_lock->fl->c.flc_file == smb_lock->fl->c.flc_file &&
7494 					    cmp_lock->start == smb_lock->start &&
7495 					    cmp_lock->end == smb_lock->end &&
7496 					    !lock_defer_pending(cmp_lock->fl)) {
7497 						nolock = 0;
7498 						list_del(&cmp_lock->flist);
7499 						list_del(&cmp_lock->clist);
7500 						spin_unlock(&conn->llist_lock);
7501 						up_read(&conn_list_lock);
7502 
7503 						locks_free_lock(cmp_lock->fl);
7504 						kfree(cmp_lock);
7505 						goto out_check_cl;
7506 					}
7507 					continue;
7508 				}
7509 
7510 				if (cmp_lock->fl->c.flc_file == smb_lock->fl->c.flc_file) {
7511 					if (smb_lock->flags & SMB2_LOCKFLAG_SHARED)
7512 						continue;
7513 				} else {
7514 					if (cmp_lock->flags & SMB2_LOCKFLAG_SHARED)
7515 						continue;
7516 				}
7517 
7518 				/* check zero byte lock range */
7519 				if (cmp_lock->zero_len && !smb_lock->zero_len &&
7520 				    cmp_lock->start > smb_lock->start &&
7521 				    cmp_lock->start < smb_lock->end) {
7522 					spin_unlock(&conn->llist_lock);
7523 					up_read(&conn_list_lock);
7524 					pr_err("previous lock conflict with zero byte lock range\n");
7525 					goto out;
7526 				}
7527 
7528 				if (smb_lock->zero_len && !cmp_lock->zero_len &&
7529 				    smb_lock->start > cmp_lock->start &&
7530 				    smb_lock->start < cmp_lock->end) {
7531 					spin_unlock(&conn->llist_lock);
7532 					up_read(&conn_list_lock);
7533 					pr_err("current lock conflict with zero byte lock range\n");
7534 					goto out;
7535 				}
7536 
7537 				if (((cmp_lock->start <= smb_lock->start &&
7538 				      cmp_lock->end > smb_lock->start) ||
7539 				     (cmp_lock->start < smb_lock->end &&
7540 				      cmp_lock->end >= smb_lock->end)) &&
7541 				    !cmp_lock->zero_len && !smb_lock->zero_len) {
7542 					spin_unlock(&conn->llist_lock);
7543 					up_read(&conn_list_lock);
7544 					pr_err("Not allow lock operation on exclusive lock range\n");
7545 					goto out;
7546 				}
7547 			}
7548 			spin_unlock(&conn->llist_lock);
7549 		}
7550 		up_read(&conn_list_lock);
7551 out_check_cl:
7552 		if (lock_is_unlock(smb_lock->fl) && nolock) {
7553 			pr_err("Try to unlock nolocked range\n");
7554 			rsp->hdr.Status = STATUS_RANGE_NOT_LOCKED;
7555 			goto out;
7556 		}
7557 
7558 no_check_cl:
7559 		flock = smb_lock->fl;
7560 		list_del(&smb_lock->llist);
7561 
7562 		if (smb_lock->zero_len) {
7563 			err = 0;
7564 			goto skip;
7565 		}
7566 retry:
7567 		rc = vfs_lock_file(filp, smb_lock->cmd, flock, NULL);
7568 skip:
7569 		if (smb_lock->flags & SMB2_LOCKFLAG_UNLOCK) {
7570 			if (!rc) {
7571 				ksmbd_debug(SMB, "File unlocked\n");
7572 			} else if (rc == -ENOENT) {
7573 				rsp->hdr.Status = STATUS_NOT_LOCKED;
7574 				goto out;
7575 			}
7576 			locks_free_lock(flock);
7577 			kfree(smb_lock);
7578 		} else {
7579 			if (rc == FILE_LOCK_DEFERRED) {
7580 				void **argv;
7581 
7582 				ksmbd_debug(SMB,
7583 					    "would have to wait for getting lock\n");
7584 				list_add(&smb_lock->llist, &rollback_list);
7585 
7586 				argv = kmalloc(sizeof(void *), KSMBD_DEFAULT_GFP);
7587 				if (!argv) {
7588 					err = -ENOMEM;
7589 					goto out;
7590 				}
7591 				argv[0] = flock;
7592 
7593 				rc = setup_async_work(work,
7594 						      smb2_remove_blocked_lock,
7595 						      argv);
7596 				if (rc) {
7597 					kfree(argv);
7598 					err = -ENOMEM;
7599 					goto out;
7600 				}
7601 				spin_lock(&fp->f_lock);
7602 				list_add(&work->fp_entry, &fp->blocked_works);
7603 				spin_unlock(&fp->f_lock);
7604 
7605 				smb2_send_interim_resp(work, STATUS_PENDING);
7606 
7607 				ksmbd_vfs_posix_lock_wait(flock);
7608 
7609 				spin_lock(&fp->f_lock);
7610 				list_del(&work->fp_entry);
7611 				spin_unlock(&fp->f_lock);
7612 
7613 				if (work->state != KSMBD_WORK_ACTIVE) {
7614 					list_del(&smb_lock->llist);
7615 					locks_free_lock(flock);
7616 
7617 					if (work->state == KSMBD_WORK_CANCELLED) {
7618 						rsp->hdr.Status =
7619 							STATUS_CANCELLED;
7620 						kfree(smb_lock);
7621 						smb2_send_interim_resp(work,
7622 								       STATUS_CANCELLED);
7623 						work->send_no_response = 1;
7624 						goto out;
7625 					}
7626 
7627 					rsp->hdr.Status =
7628 						STATUS_RANGE_NOT_LOCKED;
7629 					kfree(smb_lock);
7630 					goto out2;
7631 				}
7632 
7633 				list_del(&smb_lock->llist);
7634 				release_async_work(work);
7635 				goto retry;
7636 			} else if (!rc) {
7637 				list_add(&smb_lock->llist, &rollback_list);
7638 				spin_lock(&work->conn->llist_lock);
7639 				list_add_tail(&smb_lock->clist,
7640 					      &work->conn->lock_list);
7641 				list_add_tail(&smb_lock->flist,
7642 					      &fp->lock_list);
7643 				spin_unlock(&work->conn->llist_lock);
7644 				ksmbd_debug(SMB, "successful in taking lock\n");
7645 			} else {
7646 				goto out;
7647 			}
7648 		}
7649 	}
7650 
7651 	if (atomic_read(&fp->f_ci->op_count) > 1)
7652 		smb_break_all_oplock(work, fp);
7653 
7654 	rsp->StructureSize = cpu_to_le16(4);
7655 	ksmbd_debug(SMB, "successful in taking lock\n");
7656 	rsp->hdr.Status = STATUS_SUCCESS;
7657 	rsp->Reserved = 0;
7658 	err = ksmbd_iov_pin_rsp(work, rsp, sizeof(struct smb2_lock_rsp));
7659 	if (err)
7660 		goto out;
7661 
7662 	ksmbd_fd_put(work, fp);
7663 	return 0;
7664 
7665 out:
7666 	list_for_each_entry_safe(smb_lock, tmp, &lock_list, llist) {
7667 		locks_free_lock(smb_lock->fl);
7668 		list_del(&smb_lock->llist);
7669 		kfree(smb_lock);
7670 	}
7671 
7672 	list_for_each_entry_safe(smb_lock, tmp, &rollback_list, llist) {
7673 		struct file_lock *rlock = NULL;
7674 
7675 		rlock = smb_flock_init(filp);
7676 		rlock->c.flc_type = F_UNLCK;
7677 		rlock->fl_start = smb_lock->start;
7678 		rlock->fl_end = smb_lock->end;
7679 
7680 		rc = vfs_lock_file(filp, F_SETLK, rlock, NULL);
7681 		if (rc)
7682 			pr_err("rollback unlock fail : %d\n", rc);
7683 
7684 		list_del(&smb_lock->llist);
7685 		spin_lock(&work->conn->llist_lock);
7686 		if (!list_empty(&smb_lock->flist))
7687 			list_del(&smb_lock->flist);
7688 		list_del(&smb_lock->clist);
7689 		spin_unlock(&work->conn->llist_lock);
7690 
7691 		locks_free_lock(smb_lock->fl);
7692 		locks_free_lock(rlock);
7693 		kfree(smb_lock);
7694 	}
7695 out2:
7696 	ksmbd_debug(SMB, "failed in taking lock(flags : %x), err : %d\n", flags, err);
7697 
7698 	if (!rsp->hdr.Status) {
7699 		if (err == -EINVAL)
7700 			rsp->hdr.Status = STATUS_INVALID_PARAMETER;
7701 		else if (err == -ENOMEM)
7702 			rsp->hdr.Status = STATUS_INSUFFICIENT_RESOURCES;
7703 		else if (err == -ENOENT)
7704 			rsp->hdr.Status = STATUS_FILE_CLOSED;
7705 		else
7706 			rsp->hdr.Status = STATUS_LOCK_NOT_GRANTED;
7707 	}
7708 
7709 	smb2_set_err_rsp(work);
7710 	ksmbd_fd_put(work, fp);
7711 	return err;
7712 }
7713 
7714 static int fsctl_copychunk(struct ksmbd_work *work,
7715 			   struct copychunk_ioctl_req *ci_req,
7716 			   unsigned int cnt_code,
7717 			   unsigned int input_count,
7718 			   unsigned long long volatile_id,
7719 			   unsigned long long persistent_id,
7720 			   struct smb2_ioctl_rsp *rsp)
7721 {
7722 	struct copychunk_ioctl_rsp *ci_rsp;
7723 	struct ksmbd_file *src_fp = NULL, *dst_fp = NULL;
7724 	struct srv_copychunk *chunks;
7725 	unsigned int i, chunk_count, chunk_count_written = 0;
7726 	unsigned int chunk_size_written = 0;
7727 	loff_t total_size_written = 0;
7728 	int ret = 0;
7729 
7730 	ci_rsp = (struct copychunk_ioctl_rsp *)&rsp->Buffer[0];
7731 
7732 	rsp->VolatileFileId = volatile_id;
7733 	rsp->PersistentFileId = persistent_id;
7734 	ci_rsp->ChunksWritten =
7735 		cpu_to_le32(ksmbd_server_side_copy_max_chunk_count());
7736 	ci_rsp->ChunkBytesWritten =
7737 		cpu_to_le32(ksmbd_server_side_copy_max_chunk_size());
7738 	ci_rsp->TotalBytesWritten =
7739 		cpu_to_le32(ksmbd_server_side_copy_max_total_size());
7740 
7741 	chunk_count = le32_to_cpu(ci_req->ChunkCount);
7742 	if (chunk_count == 0)
7743 		goto out;
7744 	total_size_written = 0;
7745 
7746 	/* verify the SRV_COPYCHUNK_COPY packet */
7747 	if (chunk_count > ksmbd_server_side_copy_max_chunk_count() ||
7748 	    input_count < struct_size(ci_req, Chunks, chunk_count)) {
7749 		rsp->hdr.Status = STATUS_INVALID_PARAMETER;
7750 		return -EINVAL;
7751 	}
7752 
7753 	chunks = &ci_req->Chunks[0];
7754 	for (i = 0; i < chunk_count; i++) {
7755 		if (le32_to_cpu(chunks[i].Length) == 0 ||
7756 		    le32_to_cpu(chunks[i].Length) > ksmbd_server_side_copy_max_chunk_size())
7757 			break;
7758 		total_size_written += le32_to_cpu(chunks[i].Length);
7759 	}
7760 
7761 	if (i < chunk_count ||
7762 	    total_size_written > ksmbd_server_side_copy_max_total_size()) {
7763 		rsp->hdr.Status = STATUS_INVALID_PARAMETER;
7764 		return -EINVAL;
7765 	}
7766 
7767 	src_fp = ksmbd_lookup_foreign_fd(work,
7768 					 le64_to_cpu(ci_req->SourceKeyU64[0]));
7769 	dst_fp = ksmbd_lookup_fd_slow(work, volatile_id, persistent_id);
7770 	ret = -EINVAL;
7771 	if (!src_fp ||
7772 	    src_fp->persistent_id != le64_to_cpu(ci_req->SourceKeyU64[1])) {
7773 		rsp->hdr.Status = STATUS_OBJECT_NAME_NOT_FOUND;
7774 		goto out;
7775 	}
7776 
7777 	if (!dst_fp) {
7778 		rsp->hdr.Status = STATUS_FILE_CLOSED;
7779 		goto out;
7780 	}
7781 
7782 	/*
7783 	 * FILE_READ_DATA should only be included in
7784 	 * the FSCTL_COPYCHUNK case
7785 	 */
7786 	if (cnt_code == FSCTL_COPYCHUNK &&
7787 	    !(dst_fp->daccess & (FILE_READ_DATA_LE | FILE_GENERIC_READ_LE))) {
7788 		rsp->hdr.Status = STATUS_ACCESS_DENIED;
7789 		goto out;
7790 	}
7791 
7792 	ret = ksmbd_vfs_copy_file_ranges(work, src_fp, dst_fp,
7793 					 chunks, chunk_count,
7794 					 &chunk_count_written,
7795 					 &chunk_size_written,
7796 					 &total_size_written);
7797 	if (ret < 0) {
7798 		if (ret == -EACCES)
7799 			rsp->hdr.Status = STATUS_ACCESS_DENIED;
7800 		if (ret == -EAGAIN)
7801 			rsp->hdr.Status = STATUS_FILE_LOCK_CONFLICT;
7802 		else if (ret == -EBADF)
7803 			rsp->hdr.Status = STATUS_INVALID_HANDLE;
7804 		else if (ret == -EFBIG || ret == -ENOSPC)
7805 			rsp->hdr.Status = STATUS_DISK_FULL;
7806 		else if (ret == -EINVAL)
7807 			rsp->hdr.Status = STATUS_INVALID_PARAMETER;
7808 		else if (ret == -EISDIR)
7809 			rsp->hdr.Status = STATUS_FILE_IS_A_DIRECTORY;
7810 		else if (ret == -E2BIG)
7811 			rsp->hdr.Status = STATUS_INVALID_VIEW_SIZE;
7812 		else
7813 			rsp->hdr.Status = STATUS_UNEXPECTED_IO_ERROR;
7814 	}
7815 
7816 	ci_rsp->ChunksWritten = cpu_to_le32(chunk_count_written);
7817 	ci_rsp->ChunkBytesWritten = cpu_to_le32(chunk_size_written);
7818 	ci_rsp->TotalBytesWritten = cpu_to_le32(total_size_written);
7819 out:
7820 	ksmbd_fd_put(work, src_fp);
7821 	ksmbd_fd_put(work, dst_fp);
7822 	return ret;
7823 }
7824 
7825 static __be32 idev_ipv4_address(struct in_device *idev)
7826 {
7827 	__be32 addr = 0;
7828 
7829 	struct in_ifaddr *ifa;
7830 
7831 	rcu_read_lock();
7832 	in_dev_for_each_ifa_rcu(ifa, idev) {
7833 		if (ifa->ifa_flags & IFA_F_SECONDARY)
7834 			continue;
7835 
7836 		addr = ifa->ifa_address;
7837 		break;
7838 	}
7839 	rcu_read_unlock();
7840 	return addr;
7841 }
7842 
7843 static int fsctl_query_iface_info_ioctl(struct ksmbd_conn *conn,
7844 					struct smb2_ioctl_rsp *rsp,
7845 					unsigned int out_buf_len)
7846 {
7847 	struct network_interface_info_ioctl_rsp *nii_rsp = NULL;
7848 	int nbytes = 0;
7849 	struct net_device *netdev;
7850 	struct sockaddr_storage_rsp *sockaddr_storage;
7851 	unsigned int flags;
7852 	unsigned long long speed;
7853 
7854 	rtnl_lock();
7855 	for_each_netdev(&init_net, netdev) {
7856 		bool ipv4_set = false;
7857 
7858 		if (netdev->type == ARPHRD_LOOPBACK)
7859 			continue;
7860 
7861 		if (!ksmbd_find_netdev_name_iface_list(netdev->name))
7862 			continue;
7863 
7864 		flags = netif_get_flags(netdev);
7865 		if (!(flags & IFF_RUNNING))
7866 			continue;
7867 ipv6_retry:
7868 		if (out_buf_len <
7869 		    nbytes + sizeof(struct network_interface_info_ioctl_rsp)) {
7870 			rtnl_unlock();
7871 			return -ENOSPC;
7872 		}
7873 
7874 		nii_rsp = (struct network_interface_info_ioctl_rsp *)
7875 				&rsp->Buffer[nbytes];
7876 		nii_rsp->IfIndex = cpu_to_le32(netdev->ifindex);
7877 
7878 		nii_rsp->Capability = 0;
7879 		if (netdev->real_num_tx_queues > 1)
7880 			nii_rsp->Capability |= RSS_CAPABLE;
7881 		if (ksmbd_rdma_capable_netdev(netdev))
7882 			nii_rsp->Capability |= RDMA_CAPABLE;
7883 
7884 		nii_rsp->Next = cpu_to_le32(152);
7885 		nii_rsp->Reserved = 0;
7886 
7887 		if (netdev->ethtool_ops->get_link_ksettings) {
7888 			struct ethtool_link_ksettings cmd;
7889 
7890 			netdev->ethtool_ops->get_link_ksettings(netdev, &cmd);
7891 			speed = cmd.base.speed;
7892 		} else {
7893 			ksmbd_debug(SMB, "%s %s\n", netdev->name,
7894 				    "speed is unknown, defaulting to 1Gb/sec");
7895 			speed = SPEED_1000;
7896 		}
7897 
7898 		speed *= 1000000;
7899 		nii_rsp->LinkSpeed = cpu_to_le64(speed);
7900 
7901 		sockaddr_storage = (struct sockaddr_storage_rsp *)
7902 					nii_rsp->SockAddr_Storage;
7903 		memset(sockaddr_storage, 0, 128);
7904 
7905 		if (!ipv4_set) {
7906 			struct in_device *idev;
7907 
7908 			sockaddr_storage->Family = INTERNETWORK;
7909 			sockaddr_storage->addr4.Port = 0;
7910 
7911 			idev = __in_dev_get_rtnl(netdev);
7912 			if (!idev)
7913 				continue;
7914 			sockaddr_storage->addr4.IPv4Address =
7915 						idev_ipv4_address(idev);
7916 			nbytes += sizeof(struct network_interface_info_ioctl_rsp);
7917 			ipv4_set = true;
7918 			goto ipv6_retry;
7919 		} else {
7920 			struct inet6_dev *idev6;
7921 			struct inet6_ifaddr *ifa;
7922 			__u8 *ipv6_addr = sockaddr_storage->addr6.IPv6Address;
7923 
7924 			sockaddr_storage->Family = INTERNETWORKV6;
7925 			sockaddr_storage->addr6.Port = 0;
7926 			sockaddr_storage->addr6.FlowInfo = 0;
7927 
7928 			idev6 = __in6_dev_get(netdev);
7929 			if (!idev6)
7930 				continue;
7931 
7932 			list_for_each_entry(ifa, &idev6->addr_list, if_list) {
7933 				if (ifa->flags & (IFA_F_TENTATIVE |
7934 							IFA_F_DEPRECATED))
7935 					continue;
7936 				memcpy(ipv6_addr, ifa->addr.s6_addr, 16);
7937 				break;
7938 			}
7939 			sockaddr_storage->addr6.ScopeId = 0;
7940 			nbytes += sizeof(struct network_interface_info_ioctl_rsp);
7941 		}
7942 	}
7943 	rtnl_unlock();
7944 
7945 	/* zero if this is last one */
7946 	if (nii_rsp)
7947 		nii_rsp->Next = 0;
7948 
7949 	rsp->PersistentFileId = SMB2_NO_FID;
7950 	rsp->VolatileFileId = SMB2_NO_FID;
7951 	return nbytes;
7952 }
7953 
7954 static int fsctl_validate_negotiate_info(struct ksmbd_conn *conn,
7955 					 struct validate_negotiate_info_req *neg_req,
7956 					 struct validate_negotiate_info_rsp *neg_rsp,
7957 					 unsigned int in_buf_len)
7958 {
7959 	int ret = 0;
7960 	int dialect;
7961 
7962 	if (in_buf_len < offsetof(struct validate_negotiate_info_req, Dialects) +
7963 			le16_to_cpu(neg_req->DialectCount) * sizeof(__le16))
7964 		return -EINVAL;
7965 
7966 	dialect = ksmbd_lookup_dialect_by_id(neg_req->Dialects,
7967 					     neg_req->DialectCount);
7968 	if (dialect == BAD_PROT_ID || dialect != conn->dialect) {
7969 		ret = -EINVAL;
7970 		goto err_out;
7971 	}
7972 
7973 	if (strncmp(neg_req->Guid, conn->ClientGUID, SMB2_CLIENT_GUID_SIZE)) {
7974 		ret = -EINVAL;
7975 		goto err_out;
7976 	}
7977 
7978 	if (le16_to_cpu(neg_req->SecurityMode) != conn->cli_sec_mode) {
7979 		ret = -EINVAL;
7980 		goto err_out;
7981 	}
7982 
7983 	if (le32_to_cpu(neg_req->Capabilities) != conn->cli_cap) {
7984 		ret = -EINVAL;
7985 		goto err_out;
7986 	}
7987 
7988 	neg_rsp->Capabilities = cpu_to_le32(conn->vals->req_capabilities);
7989 	memset(neg_rsp->Guid, 0, SMB2_CLIENT_GUID_SIZE);
7990 	neg_rsp->SecurityMode = cpu_to_le16(conn->srv_sec_mode);
7991 	neg_rsp->Dialect = cpu_to_le16(conn->dialect);
7992 err_out:
7993 	return ret;
7994 }
7995 
7996 static int fsctl_query_allocated_ranges(struct ksmbd_work *work, u64 id,
7997 					struct file_allocated_range_buffer *qar_req,
7998 					struct file_allocated_range_buffer *qar_rsp,
7999 					unsigned int in_count, unsigned int *out_count)
8000 {
8001 	struct ksmbd_file *fp;
8002 	loff_t start, length;
8003 	int ret = 0;
8004 
8005 	*out_count = 0;
8006 	if (in_count == 0)
8007 		return -EINVAL;
8008 
8009 	start = le64_to_cpu(qar_req->file_offset);
8010 	length = le64_to_cpu(qar_req->length);
8011 
8012 	if (start < 0 || length < 0)
8013 		return -EINVAL;
8014 
8015 	fp = ksmbd_lookup_fd_fast(work, id);
8016 	if (!fp)
8017 		return -ENOENT;
8018 
8019 	ret = ksmbd_vfs_fqar_lseek(fp, start, length,
8020 				   qar_rsp, in_count, out_count);
8021 	if (ret && ret != -E2BIG)
8022 		*out_count = 0;
8023 
8024 	ksmbd_fd_put(work, fp);
8025 	return ret;
8026 }
8027 
8028 static int fsctl_pipe_transceive(struct ksmbd_work *work, u64 id,
8029 				 unsigned int out_buf_len,
8030 				 struct smb2_ioctl_req *req,
8031 				 struct smb2_ioctl_rsp *rsp)
8032 {
8033 	struct ksmbd_rpc_command *rpc_resp;
8034 	char *data_buf = (char *)req + le32_to_cpu(req->InputOffset);
8035 	int nbytes = 0;
8036 
8037 	rpc_resp = ksmbd_rpc_ioctl(work->sess, id, data_buf,
8038 				   le32_to_cpu(req->InputCount));
8039 	if (rpc_resp) {
8040 		if (rpc_resp->flags == KSMBD_RPC_SOME_NOT_MAPPED) {
8041 			/*
8042 			 * set STATUS_SOME_NOT_MAPPED response
8043 			 * for unknown domain sid.
8044 			 */
8045 			rsp->hdr.Status = STATUS_SOME_NOT_MAPPED;
8046 		} else if (rpc_resp->flags == KSMBD_RPC_ENOTIMPLEMENTED) {
8047 			rsp->hdr.Status = STATUS_NOT_SUPPORTED;
8048 			goto out;
8049 		} else if (rpc_resp->flags != KSMBD_RPC_OK) {
8050 			rsp->hdr.Status = STATUS_INVALID_PARAMETER;
8051 			goto out;
8052 		}
8053 
8054 		nbytes = rpc_resp->payload_sz;
8055 		if (rpc_resp->payload_sz > out_buf_len) {
8056 			rsp->hdr.Status = STATUS_BUFFER_OVERFLOW;
8057 			nbytes = out_buf_len;
8058 		}
8059 
8060 		if (!rpc_resp->payload_sz) {
8061 			rsp->hdr.Status =
8062 				STATUS_UNEXPECTED_IO_ERROR;
8063 			goto out;
8064 		}
8065 
8066 		memcpy((char *)rsp->Buffer, rpc_resp->payload, nbytes);
8067 	}
8068 out:
8069 	kvfree(rpc_resp);
8070 	return nbytes;
8071 }
8072 
8073 static inline int fsctl_set_sparse(struct ksmbd_work *work, u64 id,
8074 				   struct file_sparse *sparse)
8075 {
8076 	struct ksmbd_file *fp;
8077 	struct mnt_idmap *idmap;
8078 	int ret = 0;
8079 	__le32 old_fattr;
8080 
8081 	fp = ksmbd_lookup_fd_fast(work, id);
8082 	if (!fp)
8083 		return -ENOENT;
8084 	idmap = file_mnt_idmap(fp->filp);
8085 
8086 	old_fattr = fp->f_ci->m_fattr;
8087 	if (sparse->SetSparse)
8088 		fp->f_ci->m_fattr |= FILE_ATTRIBUTE_SPARSE_FILE_LE;
8089 	else
8090 		fp->f_ci->m_fattr &= ~FILE_ATTRIBUTE_SPARSE_FILE_LE;
8091 
8092 	if (fp->f_ci->m_fattr != old_fattr &&
8093 	    test_share_config_flag(work->tcon->share_conf,
8094 				   KSMBD_SHARE_FLAG_STORE_DOS_ATTRS)) {
8095 		struct xattr_dos_attrib da;
8096 
8097 		ret = ksmbd_vfs_get_dos_attrib_xattr(idmap,
8098 						     fp->filp->f_path.dentry, &da);
8099 		if (ret <= 0)
8100 			goto out;
8101 
8102 		da.attr = le32_to_cpu(fp->f_ci->m_fattr);
8103 		ret = ksmbd_vfs_set_dos_attrib_xattr(idmap,
8104 						     &fp->filp->f_path,
8105 						     &da, true);
8106 		if (ret)
8107 			fp->f_ci->m_fattr = old_fattr;
8108 	}
8109 
8110 out:
8111 	ksmbd_fd_put(work, fp);
8112 	return ret;
8113 }
8114 
8115 static int fsctl_request_resume_key(struct ksmbd_work *work,
8116 				    struct smb2_ioctl_req *req,
8117 				    struct resume_key_ioctl_rsp *key_rsp)
8118 {
8119 	struct ksmbd_file *fp;
8120 
8121 	fp = ksmbd_lookup_fd_slow(work, req->VolatileFileId, req->PersistentFileId);
8122 	if (!fp)
8123 		return -ENOENT;
8124 
8125 	memset(key_rsp, 0, sizeof(*key_rsp));
8126 	key_rsp->ResumeKeyU64[0] = req->VolatileFileId;
8127 	key_rsp->ResumeKeyU64[1] = req->PersistentFileId;
8128 	ksmbd_fd_put(work, fp);
8129 
8130 	return 0;
8131 }
8132 
8133 /**
8134  * smb2_ioctl() - handler for smb2 ioctl command
8135  * @work:	smb work containing ioctl command buffer
8136  *
8137  * Return:	0 on success, otherwise error
8138  */
8139 int smb2_ioctl(struct ksmbd_work *work)
8140 {
8141 	struct smb2_ioctl_req *req;
8142 	struct smb2_ioctl_rsp *rsp;
8143 	unsigned int cnt_code, nbytes = 0, out_buf_len, in_buf_len;
8144 	u64 id = KSMBD_NO_FID;
8145 	struct ksmbd_conn *conn = work->conn;
8146 	int ret = 0;
8147 	char *buffer;
8148 
8149 	ksmbd_debug(SMB, "Received smb2 ioctl request\n");
8150 
8151 	if (work->next_smb2_rcv_hdr_off) {
8152 		req = ksmbd_req_buf_next(work);
8153 		rsp = ksmbd_resp_buf_next(work);
8154 		if (!has_file_id(req->VolatileFileId)) {
8155 			ksmbd_debug(SMB, "Compound request set FID = %llu\n",
8156 				    work->compound_fid);
8157 			id = work->compound_fid;
8158 		}
8159 	} else {
8160 		req = smb_get_msg(work->request_buf);
8161 		rsp = smb_get_msg(work->response_buf);
8162 	}
8163 
8164 	if (!has_file_id(id))
8165 		id = req->VolatileFileId;
8166 
8167 	if (req->Flags != cpu_to_le32(SMB2_0_IOCTL_IS_FSCTL)) {
8168 		ret = -EOPNOTSUPP;
8169 		goto out;
8170 	}
8171 
8172 	buffer = (char *)req + le32_to_cpu(req->InputOffset);
8173 
8174 	cnt_code = le32_to_cpu(req->CtlCode);
8175 	ret = smb2_calc_max_out_buf_len(work, 48,
8176 					le32_to_cpu(req->MaxOutputResponse));
8177 	if (ret < 0) {
8178 		rsp->hdr.Status = STATUS_INVALID_PARAMETER;
8179 		goto out;
8180 	}
8181 	out_buf_len = (unsigned int)ret;
8182 	in_buf_len = le32_to_cpu(req->InputCount);
8183 
8184 	switch (cnt_code) {
8185 	case FSCTL_DFS_GET_REFERRALS:
8186 	case FSCTL_DFS_GET_REFERRALS_EX:
8187 		/* Not support DFS yet */
8188 		ret = -EOPNOTSUPP;
8189 		rsp->hdr.Status = STATUS_FS_DRIVER_REQUIRED;
8190 		goto out2;
8191 	case FSCTL_CREATE_OR_GET_OBJECT_ID:
8192 	{
8193 		struct file_object_buf_type1_ioctl_rsp *obj_buf;
8194 
8195 		nbytes = sizeof(struct file_object_buf_type1_ioctl_rsp);
8196 		obj_buf = (struct file_object_buf_type1_ioctl_rsp *)
8197 			&rsp->Buffer[0];
8198 
8199 		/*
8200 		 * TODO: This is dummy implementation to pass smbtorture
8201 		 * Need to check correct response later
8202 		 */
8203 		memset(obj_buf->ObjectId, 0x0, 16);
8204 		memset(obj_buf->BirthVolumeId, 0x0, 16);
8205 		memset(obj_buf->BirthObjectId, 0x0, 16);
8206 		memset(obj_buf->DomainId, 0x0, 16);
8207 
8208 		break;
8209 	}
8210 	case FSCTL_PIPE_TRANSCEIVE:
8211 		out_buf_len = min_t(u32, KSMBD_IPC_MAX_PAYLOAD, out_buf_len);
8212 		nbytes = fsctl_pipe_transceive(work, id, out_buf_len, req, rsp);
8213 		break;
8214 	case FSCTL_VALIDATE_NEGOTIATE_INFO:
8215 		if (conn->dialect < SMB30_PROT_ID) {
8216 			ret = -EOPNOTSUPP;
8217 			goto out;
8218 		}
8219 
8220 		if (in_buf_len < offsetof(struct validate_negotiate_info_req,
8221 					  Dialects)) {
8222 			ret = -EINVAL;
8223 			goto out;
8224 		}
8225 
8226 		if (out_buf_len < sizeof(struct validate_negotiate_info_rsp)) {
8227 			ret = -EINVAL;
8228 			goto out;
8229 		}
8230 
8231 		ret = fsctl_validate_negotiate_info(conn,
8232 			(struct validate_negotiate_info_req *)buffer,
8233 			(struct validate_negotiate_info_rsp *)&rsp->Buffer[0],
8234 			in_buf_len);
8235 		if (ret < 0)
8236 			goto out;
8237 
8238 		nbytes = sizeof(struct validate_negotiate_info_rsp);
8239 		rsp->PersistentFileId = SMB2_NO_FID;
8240 		rsp->VolatileFileId = SMB2_NO_FID;
8241 		break;
8242 	case FSCTL_QUERY_NETWORK_INTERFACE_INFO:
8243 		ret = fsctl_query_iface_info_ioctl(conn, rsp, out_buf_len);
8244 		if (ret < 0)
8245 			goto out;
8246 		nbytes = ret;
8247 		break;
8248 	case FSCTL_REQUEST_RESUME_KEY:
8249 		if (out_buf_len < sizeof(struct resume_key_ioctl_rsp)) {
8250 			ret = -EINVAL;
8251 			goto out;
8252 		}
8253 
8254 		ret = fsctl_request_resume_key(work, req,
8255 					       (struct resume_key_ioctl_rsp *)&rsp->Buffer[0]);
8256 		if (ret < 0)
8257 			goto out;
8258 		rsp->PersistentFileId = req->PersistentFileId;
8259 		rsp->VolatileFileId = req->VolatileFileId;
8260 		nbytes = sizeof(struct resume_key_ioctl_rsp);
8261 		break;
8262 	case FSCTL_COPYCHUNK:
8263 	case FSCTL_COPYCHUNK_WRITE:
8264 		if (!test_tree_conn_flag(work->tcon, KSMBD_TREE_CONN_FLAG_WRITABLE)) {
8265 			ksmbd_debug(SMB,
8266 				    "User does not have write permission\n");
8267 			ret = -EACCES;
8268 			goto out;
8269 		}
8270 
8271 		if (in_buf_len <= sizeof(struct copychunk_ioctl_req)) {
8272 			ret = -EINVAL;
8273 			goto out;
8274 		}
8275 
8276 		if (out_buf_len < sizeof(struct copychunk_ioctl_rsp)) {
8277 			ret = -EINVAL;
8278 			goto out;
8279 		}
8280 
8281 		nbytes = sizeof(struct copychunk_ioctl_rsp);
8282 		rsp->VolatileFileId = req->VolatileFileId;
8283 		rsp->PersistentFileId = req->PersistentFileId;
8284 		fsctl_copychunk(work,
8285 				(struct copychunk_ioctl_req *)buffer,
8286 				le32_to_cpu(req->CtlCode),
8287 				le32_to_cpu(req->InputCount),
8288 				req->VolatileFileId,
8289 				req->PersistentFileId,
8290 				rsp);
8291 		break;
8292 	case FSCTL_SET_SPARSE:
8293 		if (in_buf_len < sizeof(struct file_sparse)) {
8294 			ret = -EINVAL;
8295 			goto out;
8296 		}
8297 
8298 		ret = fsctl_set_sparse(work, id, (struct file_sparse *)buffer);
8299 		if (ret < 0)
8300 			goto out;
8301 		break;
8302 	case FSCTL_SET_ZERO_DATA:
8303 	{
8304 		struct file_zero_data_information *zero_data;
8305 		struct ksmbd_file *fp;
8306 		loff_t off, len, bfz;
8307 
8308 		if (!test_tree_conn_flag(work->tcon, KSMBD_TREE_CONN_FLAG_WRITABLE)) {
8309 			ksmbd_debug(SMB,
8310 				    "User does not have write permission\n");
8311 			ret = -EACCES;
8312 			goto out;
8313 		}
8314 
8315 		if (in_buf_len < sizeof(struct file_zero_data_information)) {
8316 			ret = -EINVAL;
8317 			goto out;
8318 		}
8319 
8320 		zero_data =
8321 			(struct file_zero_data_information *)buffer;
8322 
8323 		off = le64_to_cpu(zero_data->FileOffset);
8324 		bfz = le64_to_cpu(zero_data->BeyondFinalZero);
8325 		if (off < 0 || bfz < 0 || off > bfz) {
8326 			ret = -EINVAL;
8327 			goto out;
8328 		}
8329 
8330 		len = bfz - off;
8331 		if (len) {
8332 			fp = ksmbd_lookup_fd_fast(work, id);
8333 			if (!fp) {
8334 				ret = -ENOENT;
8335 				goto out;
8336 			}
8337 
8338 			ret = ksmbd_vfs_zero_data(work, fp, off, len);
8339 			ksmbd_fd_put(work, fp);
8340 			if (ret < 0)
8341 				goto out;
8342 		}
8343 		break;
8344 	}
8345 	case FSCTL_QUERY_ALLOCATED_RANGES:
8346 		if (in_buf_len < sizeof(struct file_allocated_range_buffer)) {
8347 			ret = -EINVAL;
8348 			goto out;
8349 		}
8350 
8351 		ret = fsctl_query_allocated_ranges(work, id,
8352 			(struct file_allocated_range_buffer *)buffer,
8353 			(struct file_allocated_range_buffer *)&rsp->Buffer[0],
8354 			out_buf_len /
8355 			sizeof(struct file_allocated_range_buffer), &nbytes);
8356 		if (ret == -E2BIG) {
8357 			rsp->hdr.Status = STATUS_BUFFER_OVERFLOW;
8358 		} else if (ret < 0) {
8359 			nbytes = 0;
8360 			goto out;
8361 		}
8362 
8363 		nbytes *= sizeof(struct file_allocated_range_buffer);
8364 		break;
8365 	case FSCTL_GET_REPARSE_POINT:
8366 	{
8367 		struct reparse_data_buffer *reparse_ptr;
8368 		struct ksmbd_file *fp;
8369 
8370 		reparse_ptr = (struct reparse_data_buffer *)&rsp->Buffer[0];
8371 		fp = ksmbd_lookup_fd_fast(work, id);
8372 		if (!fp) {
8373 			pr_err("not found fp!!\n");
8374 			ret = -ENOENT;
8375 			goto out;
8376 		}
8377 
8378 		reparse_ptr->ReparseTag =
8379 			smb2_get_reparse_tag_special_file(file_inode(fp->filp)->i_mode);
8380 		reparse_ptr->ReparseDataLength = 0;
8381 		ksmbd_fd_put(work, fp);
8382 		nbytes = sizeof(struct reparse_data_buffer);
8383 		break;
8384 	}
8385 	case FSCTL_DUPLICATE_EXTENTS_TO_FILE:
8386 	{
8387 		struct ksmbd_file *fp_in, *fp_out = NULL;
8388 		struct duplicate_extents_to_file *dup_ext;
8389 		loff_t src_off, dst_off, length, cloned;
8390 
8391 		if (in_buf_len < sizeof(struct duplicate_extents_to_file)) {
8392 			ret = -EINVAL;
8393 			goto out;
8394 		}
8395 
8396 		dup_ext = (struct duplicate_extents_to_file *)buffer;
8397 
8398 		fp_in = ksmbd_lookup_fd_slow(work, dup_ext->VolatileFileHandle,
8399 					     dup_ext->PersistentFileHandle);
8400 		if (!fp_in) {
8401 			pr_err("not found file handle in duplicate extent to file\n");
8402 			ret = -ENOENT;
8403 			goto out;
8404 		}
8405 
8406 		fp_out = ksmbd_lookup_fd_fast(work, id);
8407 		if (!fp_out) {
8408 			pr_err("not found fp\n");
8409 			ret = -ENOENT;
8410 			goto dup_ext_out;
8411 		}
8412 
8413 		src_off = le64_to_cpu(dup_ext->SourceFileOffset);
8414 		dst_off = le64_to_cpu(dup_ext->TargetFileOffset);
8415 		length = le64_to_cpu(dup_ext->ByteCount);
8416 		/*
8417 		 * XXX: It is not clear if FSCTL_DUPLICATE_EXTENTS_TO_FILE
8418 		 * should fall back to vfs_copy_file_range().  This could be
8419 		 * beneficial when re-exporting nfs/smb mount, but note that
8420 		 * this can result in partial copy that returns an error status.
8421 		 * If/when FSCTL_DUPLICATE_EXTENTS_TO_FILE_EX is implemented,
8422 		 * fall back to vfs_copy_file_range(), should be avoided when
8423 		 * the flag DUPLICATE_EXTENTS_DATA_EX_SOURCE_ATOMIC is set.
8424 		 */
8425 		cloned = vfs_clone_file_range(fp_in->filp, src_off,
8426 					      fp_out->filp, dst_off, length, 0);
8427 		if (cloned == -EXDEV || cloned == -EOPNOTSUPP) {
8428 			ret = -EOPNOTSUPP;
8429 			goto dup_ext_out;
8430 		} else if (cloned != length) {
8431 			cloned = vfs_copy_file_range(fp_in->filp, src_off,
8432 						     fp_out->filp, dst_off,
8433 						     length, 0);
8434 			if (cloned != length) {
8435 				if (cloned < 0)
8436 					ret = cloned;
8437 				else
8438 					ret = -EINVAL;
8439 			}
8440 		}
8441 
8442 dup_ext_out:
8443 		ksmbd_fd_put(work, fp_in);
8444 		ksmbd_fd_put(work, fp_out);
8445 		if (ret < 0)
8446 			goto out;
8447 		break;
8448 	}
8449 	default:
8450 		ksmbd_debug(SMB, "not implemented yet ioctl command 0x%x\n",
8451 			    cnt_code);
8452 		ret = -EOPNOTSUPP;
8453 		goto out;
8454 	}
8455 
8456 	rsp->CtlCode = cpu_to_le32(cnt_code);
8457 	rsp->InputCount = cpu_to_le32(0);
8458 	rsp->InputOffset = cpu_to_le32(112);
8459 	rsp->OutputOffset = cpu_to_le32(112);
8460 	rsp->OutputCount = cpu_to_le32(nbytes);
8461 	rsp->StructureSize = cpu_to_le16(49);
8462 	rsp->Reserved = cpu_to_le16(0);
8463 	rsp->Flags = cpu_to_le32(0);
8464 	rsp->Reserved2 = cpu_to_le32(0);
8465 	ret = ksmbd_iov_pin_rsp(work, rsp, sizeof(struct smb2_ioctl_rsp) + nbytes);
8466 	if (!ret)
8467 		return ret;
8468 
8469 out:
8470 	if (ret == -EACCES)
8471 		rsp->hdr.Status = STATUS_ACCESS_DENIED;
8472 	else if (ret == -ENOENT)
8473 		rsp->hdr.Status = STATUS_OBJECT_NAME_NOT_FOUND;
8474 	else if (ret == -EOPNOTSUPP)
8475 		rsp->hdr.Status = STATUS_NOT_SUPPORTED;
8476 	else if (ret == -ENOSPC)
8477 		rsp->hdr.Status = STATUS_BUFFER_TOO_SMALL;
8478 	else if (ret < 0 || rsp->hdr.Status == 0)
8479 		rsp->hdr.Status = STATUS_INVALID_PARAMETER;
8480 
8481 out2:
8482 	smb2_set_err_rsp(work);
8483 	return ret;
8484 }
8485 
8486 /**
8487  * smb20_oplock_break_ack() - handler for smb2.0 oplock break command
8488  * @work:	smb work containing oplock break command buffer
8489  *
8490  * Return:	0
8491  */
8492 static void smb20_oplock_break_ack(struct ksmbd_work *work)
8493 {
8494 	struct smb2_oplock_break *req;
8495 	struct smb2_oplock_break *rsp;
8496 	struct ksmbd_file *fp;
8497 	struct oplock_info *opinfo = NULL;
8498 	__le32 err = 0;
8499 	int ret = 0;
8500 	u64 volatile_id, persistent_id;
8501 	char req_oplevel = 0, rsp_oplevel = 0;
8502 	unsigned int oplock_change_type;
8503 
8504 	WORK_BUFFERS(work, req, rsp);
8505 
8506 	volatile_id = req->VolatileFid;
8507 	persistent_id = req->PersistentFid;
8508 	req_oplevel = req->OplockLevel;
8509 	ksmbd_debug(OPLOCK, "v_id %llu, p_id %llu request oplock level %d\n",
8510 		    volatile_id, persistent_id, req_oplevel);
8511 
8512 	fp = ksmbd_lookup_fd_slow(work, volatile_id, persistent_id);
8513 	if (!fp) {
8514 		rsp->hdr.Status = STATUS_FILE_CLOSED;
8515 		smb2_set_err_rsp(work);
8516 		return;
8517 	}
8518 
8519 	opinfo = opinfo_get(fp);
8520 	if (!opinfo) {
8521 		pr_err("unexpected null oplock_info\n");
8522 		rsp->hdr.Status = STATUS_INVALID_OPLOCK_PROTOCOL;
8523 		smb2_set_err_rsp(work);
8524 		ksmbd_fd_put(work, fp);
8525 		return;
8526 	}
8527 
8528 	if (opinfo->level == SMB2_OPLOCK_LEVEL_NONE) {
8529 		rsp->hdr.Status = STATUS_INVALID_OPLOCK_PROTOCOL;
8530 		goto err_out;
8531 	}
8532 
8533 	if (opinfo->op_state == OPLOCK_STATE_NONE) {
8534 		ksmbd_debug(SMB, "unexpected oplock state 0x%x\n", opinfo->op_state);
8535 		rsp->hdr.Status = STATUS_UNSUCCESSFUL;
8536 		goto err_out;
8537 	}
8538 
8539 	if ((opinfo->level == SMB2_OPLOCK_LEVEL_EXCLUSIVE ||
8540 	     opinfo->level == SMB2_OPLOCK_LEVEL_BATCH) &&
8541 	    (req_oplevel != SMB2_OPLOCK_LEVEL_II &&
8542 	     req_oplevel != SMB2_OPLOCK_LEVEL_NONE)) {
8543 		err = STATUS_INVALID_OPLOCK_PROTOCOL;
8544 		oplock_change_type = OPLOCK_WRITE_TO_NONE;
8545 	} else if (opinfo->level == SMB2_OPLOCK_LEVEL_II &&
8546 		   req_oplevel != SMB2_OPLOCK_LEVEL_NONE) {
8547 		err = STATUS_INVALID_OPLOCK_PROTOCOL;
8548 		oplock_change_type = OPLOCK_READ_TO_NONE;
8549 	} else if (req_oplevel == SMB2_OPLOCK_LEVEL_II ||
8550 		   req_oplevel == SMB2_OPLOCK_LEVEL_NONE) {
8551 		err = STATUS_INVALID_DEVICE_STATE;
8552 		if ((opinfo->level == SMB2_OPLOCK_LEVEL_EXCLUSIVE ||
8553 		     opinfo->level == SMB2_OPLOCK_LEVEL_BATCH) &&
8554 		    req_oplevel == SMB2_OPLOCK_LEVEL_II) {
8555 			oplock_change_type = OPLOCK_WRITE_TO_READ;
8556 		} else if ((opinfo->level == SMB2_OPLOCK_LEVEL_EXCLUSIVE ||
8557 			    opinfo->level == SMB2_OPLOCK_LEVEL_BATCH) &&
8558 			   req_oplevel == SMB2_OPLOCK_LEVEL_NONE) {
8559 			oplock_change_type = OPLOCK_WRITE_TO_NONE;
8560 		} else if (opinfo->level == SMB2_OPLOCK_LEVEL_II &&
8561 			   req_oplevel == SMB2_OPLOCK_LEVEL_NONE) {
8562 			oplock_change_type = OPLOCK_READ_TO_NONE;
8563 		} else {
8564 			oplock_change_type = 0;
8565 		}
8566 	} else {
8567 		oplock_change_type = 0;
8568 	}
8569 
8570 	switch (oplock_change_type) {
8571 	case OPLOCK_WRITE_TO_READ:
8572 		ret = opinfo_write_to_read(opinfo);
8573 		rsp_oplevel = SMB2_OPLOCK_LEVEL_II;
8574 		break;
8575 	case OPLOCK_WRITE_TO_NONE:
8576 		ret = opinfo_write_to_none(opinfo);
8577 		rsp_oplevel = SMB2_OPLOCK_LEVEL_NONE;
8578 		break;
8579 	case OPLOCK_READ_TO_NONE:
8580 		ret = opinfo_read_to_none(opinfo);
8581 		rsp_oplevel = SMB2_OPLOCK_LEVEL_NONE;
8582 		break;
8583 	default:
8584 		pr_err("unknown oplock change 0x%x -> 0x%x\n",
8585 		       opinfo->level, rsp_oplevel);
8586 	}
8587 
8588 	if (ret < 0) {
8589 		rsp->hdr.Status = err;
8590 		goto err_out;
8591 	}
8592 
8593 	rsp->StructureSize = cpu_to_le16(24);
8594 	rsp->OplockLevel = rsp_oplevel;
8595 	rsp->Reserved = 0;
8596 	rsp->Reserved2 = 0;
8597 	rsp->VolatileFid = volatile_id;
8598 	rsp->PersistentFid = persistent_id;
8599 	ret = ksmbd_iov_pin_rsp(work, rsp, sizeof(struct smb2_oplock_break));
8600 	if (ret) {
8601 err_out:
8602 		smb2_set_err_rsp(work);
8603 	}
8604 
8605 	opinfo->op_state = OPLOCK_STATE_NONE;
8606 	wake_up_interruptible_all(&opinfo->oplock_q);
8607 	opinfo_put(opinfo);
8608 	ksmbd_fd_put(work, fp);
8609 }
8610 
8611 static int check_lease_state(struct lease *lease, __le32 req_state)
8612 {
8613 	if ((lease->new_state ==
8614 	     (SMB2_LEASE_READ_CACHING_LE | SMB2_LEASE_HANDLE_CACHING_LE)) &&
8615 	    !(req_state & SMB2_LEASE_WRITE_CACHING_LE)) {
8616 		lease->new_state = req_state;
8617 		return 0;
8618 	}
8619 
8620 	if (lease->new_state == req_state)
8621 		return 0;
8622 
8623 	return 1;
8624 }
8625 
8626 /**
8627  * smb21_lease_break_ack() - handler for smb2.1 lease break command
8628  * @work:	smb work containing lease break command buffer
8629  *
8630  * Return:	0
8631  */
8632 static void smb21_lease_break_ack(struct ksmbd_work *work)
8633 {
8634 	struct ksmbd_conn *conn = work->conn;
8635 	struct smb2_lease_ack *req;
8636 	struct smb2_lease_ack *rsp;
8637 	struct oplock_info *opinfo;
8638 	__le32 err = 0;
8639 	int ret = 0;
8640 	unsigned int lease_change_type;
8641 	__le32 lease_state;
8642 	struct lease *lease;
8643 
8644 	WORK_BUFFERS(work, req, rsp);
8645 
8646 	ksmbd_debug(OPLOCK, "smb21 lease break, lease state(0x%x)\n",
8647 		    le32_to_cpu(req->LeaseState));
8648 	opinfo = lookup_lease_in_table(conn, req->LeaseKey);
8649 	if (!opinfo) {
8650 		ksmbd_debug(OPLOCK, "file not opened\n");
8651 		smb2_set_err_rsp(work);
8652 		rsp->hdr.Status = STATUS_UNSUCCESSFUL;
8653 		return;
8654 	}
8655 	lease = opinfo->o_lease;
8656 
8657 	if (opinfo->op_state == OPLOCK_STATE_NONE) {
8658 		pr_err("unexpected lease break state 0x%x\n",
8659 		       opinfo->op_state);
8660 		rsp->hdr.Status = STATUS_UNSUCCESSFUL;
8661 		goto err_out;
8662 	}
8663 
8664 	if (check_lease_state(lease, req->LeaseState)) {
8665 		rsp->hdr.Status = STATUS_REQUEST_NOT_ACCEPTED;
8666 		ksmbd_debug(OPLOCK,
8667 			    "req lease state: 0x%x, expected state: 0x%x\n",
8668 			    req->LeaseState, lease->new_state);
8669 		goto err_out;
8670 	}
8671 
8672 	if (!atomic_read(&opinfo->breaking_cnt)) {
8673 		rsp->hdr.Status = STATUS_UNSUCCESSFUL;
8674 		goto err_out;
8675 	}
8676 
8677 	/* check for bad lease state */
8678 	if (req->LeaseState &
8679 	    (~(SMB2_LEASE_READ_CACHING_LE | SMB2_LEASE_HANDLE_CACHING_LE))) {
8680 		err = STATUS_INVALID_OPLOCK_PROTOCOL;
8681 		if (lease->state & SMB2_LEASE_WRITE_CACHING_LE)
8682 			lease_change_type = OPLOCK_WRITE_TO_NONE;
8683 		else
8684 			lease_change_type = OPLOCK_READ_TO_NONE;
8685 		ksmbd_debug(OPLOCK, "handle bad lease state 0x%x -> 0x%x\n",
8686 			    le32_to_cpu(lease->state),
8687 			    le32_to_cpu(req->LeaseState));
8688 	} else if (lease->state == SMB2_LEASE_READ_CACHING_LE &&
8689 		   req->LeaseState != SMB2_LEASE_NONE_LE) {
8690 		err = STATUS_INVALID_OPLOCK_PROTOCOL;
8691 		lease_change_type = OPLOCK_READ_TO_NONE;
8692 		ksmbd_debug(OPLOCK, "handle bad lease state 0x%x -> 0x%x\n",
8693 			    le32_to_cpu(lease->state),
8694 			    le32_to_cpu(req->LeaseState));
8695 	} else {
8696 		/* valid lease state changes */
8697 		err = STATUS_INVALID_DEVICE_STATE;
8698 		if (req->LeaseState == SMB2_LEASE_NONE_LE) {
8699 			if (lease->state & SMB2_LEASE_WRITE_CACHING_LE)
8700 				lease_change_type = OPLOCK_WRITE_TO_NONE;
8701 			else
8702 				lease_change_type = OPLOCK_READ_TO_NONE;
8703 		} else if (req->LeaseState & SMB2_LEASE_READ_CACHING_LE) {
8704 			if (lease->state & SMB2_LEASE_WRITE_CACHING_LE)
8705 				lease_change_type = OPLOCK_WRITE_TO_READ;
8706 			else
8707 				lease_change_type = OPLOCK_READ_HANDLE_TO_READ;
8708 		} else {
8709 			lease_change_type = 0;
8710 		}
8711 	}
8712 
8713 	switch (lease_change_type) {
8714 	case OPLOCK_WRITE_TO_READ:
8715 		ret = opinfo_write_to_read(opinfo);
8716 		break;
8717 	case OPLOCK_READ_HANDLE_TO_READ:
8718 		ret = opinfo_read_handle_to_read(opinfo);
8719 		break;
8720 	case OPLOCK_WRITE_TO_NONE:
8721 		ret = opinfo_write_to_none(opinfo);
8722 		break;
8723 	case OPLOCK_READ_TO_NONE:
8724 		ret = opinfo_read_to_none(opinfo);
8725 		break;
8726 	default:
8727 		ksmbd_debug(OPLOCK, "unknown lease change 0x%x -> 0x%x\n",
8728 			    le32_to_cpu(lease->state),
8729 			    le32_to_cpu(req->LeaseState));
8730 	}
8731 
8732 	if (ret < 0) {
8733 		rsp->hdr.Status = err;
8734 		goto err_out;
8735 	}
8736 
8737 	lease_state = lease->state;
8738 
8739 	rsp->StructureSize = cpu_to_le16(36);
8740 	rsp->Reserved = 0;
8741 	rsp->Flags = 0;
8742 	memcpy(rsp->LeaseKey, req->LeaseKey, 16);
8743 	rsp->LeaseState = lease_state;
8744 	rsp->LeaseDuration = 0;
8745 	ret = ksmbd_iov_pin_rsp(work, rsp, sizeof(struct smb2_lease_ack));
8746 	if (ret) {
8747 err_out:
8748 		smb2_set_err_rsp(work);
8749 	}
8750 
8751 	opinfo->op_state = OPLOCK_STATE_NONE;
8752 	wake_up_interruptible_all(&opinfo->oplock_q);
8753 	atomic_dec(&opinfo->breaking_cnt);
8754 	wake_up_interruptible_all(&opinfo->oplock_brk);
8755 	opinfo_put(opinfo);
8756 }
8757 
8758 /**
8759  * smb2_oplock_break() - dispatcher for smb2.0 and 2.1 oplock/lease break
8760  * @work:	smb work containing oplock/lease break command buffer
8761  *
8762  * Return:	0 on success, otherwise error
8763  */
8764 int smb2_oplock_break(struct ksmbd_work *work)
8765 {
8766 	struct smb2_oplock_break *req;
8767 	struct smb2_oplock_break *rsp;
8768 
8769 	ksmbd_debug(SMB, "Received smb2 oplock break acknowledgment request\n");
8770 
8771 	WORK_BUFFERS(work, req, rsp);
8772 
8773 	switch (le16_to_cpu(req->StructureSize)) {
8774 	case OP_BREAK_STRUCT_SIZE_20:
8775 		smb20_oplock_break_ack(work);
8776 		break;
8777 	case OP_BREAK_STRUCT_SIZE_21:
8778 		smb21_lease_break_ack(work);
8779 		break;
8780 	default:
8781 		ksmbd_debug(OPLOCK, "invalid break cmd %d\n",
8782 			    le16_to_cpu(req->StructureSize));
8783 		rsp->hdr.Status = STATUS_INVALID_PARAMETER;
8784 		smb2_set_err_rsp(work);
8785 		return -EINVAL;
8786 	}
8787 
8788 	return 0;
8789 }
8790 
8791 /**
8792  * smb2_notify() - handler for smb2 notify request
8793  * @work:   smb work containing notify command buffer
8794  *
8795  * Return:      0 on success, otherwise error
8796  */
8797 int smb2_notify(struct ksmbd_work *work)
8798 {
8799 	struct smb2_change_notify_req *req;
8800 	struct smb2_change_notify_rsp *rsp;
8801 
8802 	ksmbd_debug(SMB, "Received smb2 notify\n");
8803 
8804 	WORK_BUFFERS(work, req, rsp);
8805 
8806 	if (work->next_smb2_rcv_hdr_off && req->hdr.NextCommand) {
8807 		rsp->hdr.Status = STATUS_INTERNAL_ERROR;
8808 		smb2_set_err_rsp(work);
8809 		return -EIO;
8810 	}
8811 
8812 	smb2_set_err_rsp(work);
8813 	rsp->hdr.Status = STATUS_NOT_IMPLEMENTED;
8814 	return -EOPNOTSUPP;
8815 }
8816 
8817 /**
8818  * smb2_is_sign_req() - handler for checking packet signing status
8819  * @work:	smb work containing notify command buffer
8820  * @command:	SMB2 command id
8821  *
8822  * Return:	true if packed is signed, false otherwise
8823  */
8824 bool smb2_is_sign_req(struct ksmbd_work *work, unsigned int command)
8825 {
8826 	struct smb2_hdr *rcv_hdr2 = smb_get_msg(work->request_buf);
8827 
8828 	if ((rcv_hdr2->Flags & SMB2_FLAGS_SIGNED) &&
8829 	    command != SMB2_NEGOTIATE_HE &&
8830 	    command != SMB2_SESSION_SETUP_HE &&
8831 	    command != SMB2_OPLOCK_BREAK_HE)
8832 		return true;
8833 
8834 	return false;
8835 }
8836 
8837 /**
8838  * smb2_check_sign_req() - handler for req packet sign processing
8839  * @work:   smb work containing notify command buffer
8840  *
8841  * Return:	1 on success, 0 otherwise
8842  */
8843 int smb2_check_sign_req(struct ksmbd_work *work)
8844 {
8845 	struct smb2_hdr *hdr;
8846 	char signature_req[SMB2_SIGNATURE_SIZE];
8847 	char signature[SMB2_HMACSHA256_SIZE];
8848 	struct kvec iov[1];
8849 	size_t len;
8850 
8851 	hdr = smb_get_msg(work->request_buf);
8852 	if (work->next_smb2_rcv_hdr_off)
8853 		hdr = ksmbd_req_buf_next(work);
8854 
8855 	if (!hdr->NextCommand && !work->next_smb2_rcv_hdr_off)
8856 		len = get_rfc1002_len(work->request_buf);
8857 	else if (hdr->NextCommand)
8858 		len = le32_to_cpu(hdr->NextCommand);
8859 	else
8860 		len = get_rfc1002_len(work->request_buf) -
8861 			work->next_smb2_rcv_hdr_off;
8862 
8863 	memcpy(signature_req, hdr->Signature, SMB2_SIGNATURE_SIZE);
8864 	memset(hdr->Signature, 0, SMB2_SIGNATURE_SIZE);
8865 
8866 	iov[0].iov_base = (char *)&hdr->ProtocolId;
8867 	iov[0].iov_len = len;
8868 
8869 	ksmbd_sign_smb2_pdu(work->conn, work->sess->sess_key, iov, 1,
8870 			    signature);
8871 
8872 	if (memcmp(signature, signature_req, SMB2_SIGNATURE_SIZE)) {
8873 		pr_err("bad smb2 signature\n");
8874 		return 0;
8875 	}
8876 
8877 	return 1;
8878 }
8879 
8880 /**
8881  * smb2_set_sign_rsp() - handler for rsp packet sign processing
8882  * @work:   smb work containing notify command buffer
8883  *
8884  */
8885 void smb2_set_sign_rsp(struct ksmbd_work *work)
8886 {
8887 	struct smb2_hdr *hdr;
8888 	char signature[SMB2_HMACSHA256_SIZE];
8889 	struct kvec *iov;
8890 	int n_vec = 1;
8891 
8892 	hdr = ksmbd_resp_buf_curr(work);
8893 	hdr->Flags |= SMB2_FLAGS_SIGNED;
8894 	memset(hdr->Signature, 0, SMB2_SIGNATURE_SIZE);
8895 
8896 	if (hdr->Command == SMB2_READ) {
8897 		iov = &work->iov[work->iov_idx - 1];
8898 		n_vec++;
8899 	} else {
8900 		iov = &work->iov[work->iov_idx];
8901 	}
8902 
8903 	ksmbd_sign_smb2_pdu(work->conn, work->sess->sess_key, iov, n_vec,
8904 			    signature);
8905 	memcpy(hdr->Signature, signature, SMB2_SIGNATURE_SIZE);
8906 }
8907 
8908 /**
8909  * smb3_check_sign_req() - handler for req packet sign processing
8910  * @work:   smb work containing notify command buffer
8911  *
8912  * Return:	1 on success, 0 otherwise
8913  */
8914 int smb3_check_sign_req(struct ksmbd_work *work)
8915 {
8916 	struct ksmbd_conn *conn = work->conn;
8917 	char *signing_key;
8918 	struct smb2_hdr *hdr;
8919 	struct channel *chann;
8920 	char signature_req[SMB2_SIGNATURE_SIZE];
8921 	char signature[SMB2_CMACAES_SIZE];
8922 	struct kvec iov[1];
8923 	size_t len;
8924 
8925 	hdr = smb_get_msg(work->request_buf);
8926 	if (work->next_smb2_rcv_hdr_off)
8927 		hdr = ksmbd_req_buf_next(work);
8928 
8929 	if (!hdr->NextCommand && !work->next_smb2_rcv_hdr_off)
8930 		len = get_rfc1002_len(work->request_buf);
8931 	else if (hdr->NextCommand)
8932 		len = le32_to_cpu(hdr->NextCommand);
8933 	else
8934 		len = get_rfc1002_len(work->request_buf) -
8935 			work->next_smb2_rcv_hdr_off;
8936 
8937 	if (le16_to_cpu(hdr->Command) == SMB2_SESSION_SETUP_HE) {
8938 		signing_key = work->sess->smb3signingkey;
8939 	} else {
8940 		chann = lookup_chann_list(work->sess, conn);
8941 		if (!chann) {
8942 			return 0;
8943 		}
8944 		signing_key = chann->smb3signingkey;
8945 	}
8946 
8947 	if (!signing_key) {
8948 		pr_err("SMB3 signing key is not generated\n");
8949 		return 0;
8950 	}
8951 
8952 	memcpy(signature_req, hdr->Signature, SMB2_SIGNATURE_SIZE);
8953 	memset(hdr->Signature, 0, SMB2_SIGNATURE_SIZE);
8954 	iov[0].iov_base = (char *)&hdr->ProtocolId;
8955 	iov[0].iov_len = len;
8956 
8957 	if (ksmbd_sign_smb3_pdu(conn, signing_key, iov, 1, signature))
8958 		return 0;
8959 
8960 	if (memcmp(signature, signature_req, SMB2_SIGNATURE_SIZE)) {
8961 		pr_err("bad smb2 signature\n");
8962 		return 0;
8963 	}
8964 
8965 	return 1;
8966 }
8967 
8968 /**
8969  * smb3_set_sign_rsp() - handler for rsp packet sign processing
8970  * @work:   smb work containing notify command buffer
8971  *
8972  */
8973 void smb3_set_sign_rsp(struct ksmbd_work *work)
8974 {
8975 	struct ksmbd_conn *conn = work->conn;
8976 	struct smb2_hdr *hdr;
8977 	struct channel *chann;
8978 	char signature[SMB2_CMACAES_SIZE];
8979 	struct kvec *iov;
8980 	int n_vec = 1;
8981 	char *signing_key;
8982 
8983 	hdr = ksmbd_resp_buf_curr(work);
8984 
8985 	if (conn->binding == false &&
8986 	    le16_to_cpu(hdr->Command) == SMB2_SESSION_SETUP_HE) {
8987 		signing_key = work->sess->smb3signingkey;
8988 	} else {
8989 		chann = lookup_chann_list(work->sess, work->conn);
8990 		if (!chann) {
8991 			return;
8992 		}
8993 		signing_key = chann->smb3signingkey;
8994 	}
8995 
8996 	if (!signing_key)
8997 		return;
8998 
8999 	hdr->Flags |= SMB2_FLAGS_SIGNED;
9000 	memset(hdr->Signature, 0, SMB2_SIGNATURE_SIZE);
9001 
9002 	if (hdr->Command == SMB2_READ) {
9003 		iov = &work->iov[work->iov_idx - 1];
9004 		n_vec++;
9005 	} else {
9006 		iov = &work->iov[work->iov_idx];
9007 	}
9008 
9009 	if (!ksmbd_sign_smb3_pdu(conn, signing_key, iov, n_vec,
9010 				 signature))
9011 		memcpy(hdr->Signature, signature, SMB2_SIGNATURE_SIZE);
9012 }
9013 
9014 /**
9015  * smb3_preauth_hash_rsp() - handler for computing preauth hash on response
9016  * @work:   smb work containing response buffer
9017  *
9018  */
9019 void smb3_preauth_hash_rsp(struct ksmbd_work *work)
9020 {
9021 	struct ksmbd_conn *conn = work->conn;
9022 	struct ksmbd_session *sess = work->sess;
9023 	struct smb2_hdr *req, *rsp;
9024 
9025 	if (conn->dialect != SMB311_PROT_ID)
9026 		return;
9027 
9028 	WORK_BUFFERS(work, req, rsp);
9029 
9030 	if (le16_to_cpu(req->Command) == SMB2_NEGOTIATE_HE &&
9031 	    conn->preauth_info)
9032 		ksmbd_gen_preauth_integrity_hash(conn, work->response_buf,
9033 						 conn->preauth_info->Preauth_HashValue);
9034 
9035 	if (le16_to_cpu(rsp->Command) == SMB2_SESSION_SETUP_HE && sess) {
9036 		__u8 *hash_value;
9037 
9038 		if (conn->binding) {
9039 			struct preauth_session *preauth_sess;
9040 
9041 			preauth_sess = ksmbd_preauth_session_lookup(conn, sess->id);
9042 			if (!preauth_sess)
9043 				return;
9044 			hash_value = preauth_sess->Preauth_HashValue;
9045 		} else {
9046 			hash_value = sess->Preauth_HashValue;
9047 			if (!hash_value)
9048 				return;
9049 		}
9050 		ksmbd_gen_preauth_integrity_hash(conn, work->response_buf,
9051 						 hash_value);
9052 	}
9053 }
9054 
9055 static void fill_transform_hdr(void *tr_buf, char *old_buf, __le16 cipher_type)
9056 {
9057 	struct smb2_transform_hdr *tr_hdr = tr_buf + 4;
9058 	struct smb2_hdr *hdr = smb_get_msg(old_buf);
9059 	unsigned int orig_len = get_rfc1002_len(old_buf);
9060 
9061 	/* tr_buf must be cleared by the caller */
9062 	tr_hdr->ProtocolId = SMB2_TRANSFORM_PROTO_NUM;
9063 	tr_hdr->OriginalMessageSize = cpu_to_le32(orig_len);
9064 	tr_hdr->Flags = cpu_to_le16(TRANSFORM_FLAG_ENCRYPTED);
9065 	if (cipher_type == SMB2_ENCRYPTION_AES128_GCM ||
9066 	    cipher_type == SMB2_ENCRYPTION_AES256_GCM)
9067 		get_random_bytes(&tr_hdr->Nonce, SMB3_AES_GCM_NONCE);
9068 	else
9069 		get_random_bytes(&tr_hdr->Nonce, SMB3_AES_CCM_NONCE);
9070 	memcpy(&tr_hdr->SessionId, &hdr->SessionId, 8);
9071 	inc_rfc1001_len(tr_buf, sizeof(struct smb2_transform_hdr));
9072 	inc_rfc1001_len(tr_buf, orig_len);
9073 }
9074 
9075 int smb3_encrypt_resp(struct ksmbd_work *work)
9076 {
9077 	struct kvec *iov = work->iov;
9078 	int rc = -ENOMEM;
9079 	void *tr_buf;
9080 
9081 	tr_buf = kzalloc(sizeof(struct smb2_transform_hdr) + 4, KSMBD_DEFAULT_GFP);
9082 	if (!tr_buf)
9083 		return rc;
9084 
9085 	/* fill transform header */
9086 	fill_transform_hdr(tr_buf, work->response_buf, work->conn->cipher_type);
9087 
9088 	iov[0].iov_base = tr_buf;
9089 	iov[0].iov_len = sizeof(struct smb2_transform_hdr) + 4;
9090 	work->tr_buf = tr_buf;
9091 
9092 	return ksmbd_crypt_message(work, iov, work->iov_idx + 1, 1);
9093 }
9094 
9095 bool smb3_is_transform_hdr(void *buf)
9096 {
9097 	struct smb2_transform_hdr *trhdr = smb_get_msg(buf);
9098 
9099 	return trhdr->ProtocolId == SMB2_TRANSFORM_PROTO_NUM;
9100 }
9101 
9102 int smb3_decrypt_req(struct ksmbd_work *work)
9103 {
9104 	struct ksmbd_session *sess;
9105 	char *buf = work->request_buf;
9106 	unsigned int pdu_length = get_rfc1002_len(buf);
9107 	struct kvec iov[2];
9108 	int buf_data_size = pdu_length - sizeof(struct smb2_transform_hdr);
9109 	struct smb2_transform_hdr *tr_hdr = smb_get_msg(buf);
9110 	int rc = 0;
9111 
9112 	if (pdu_length < sizeof(struct smb2_transform_hdr) ||
9113 	    buf_data_size < sizeof(struct smb2_hdr)) {
9114 		pr_err("Transform message is too small (%u)\n",
9115 		       pdu_length);
9116 		return -ECONNABORTED;
9117 	}
9118 
9119 	if (buf_data_size < le32_to_cpu(tr_hdr->OriginalMessageSize)) {
9120 		pr_err("Transform message is broken\n");
9121 		return -ECONNABORTED;
9122 	}
9123 
9124 	sess = ksmbd_session_lookup_all(work->conn, le64_to_cpu(tr_hdr->SessionId));
9125 	if (!sess) {
9126 		pr_err("invalid session id(%llx) in transform header\n",
9127 		       le64_to_cpu(tr_hdr->SessionId));
9128 		return -ECONNABORTED;
9129 	}
9130 	ksmbd_user_session_put(sess);
9131 
9132 	iov[0].iov_base = buf;
9133 	iov[0].iov_len = sizeof(struct smb2_transform_hdr) + 4;
9134 	iov[1].iov_base = buf + sizeof(struct smb2_transform_hdr) + 4;
9135 	iov[1].iov_len = buf_data_size;
9136 	rc = ksmbd_crypt_message(work, iov, 2, 0);
9137 	if (rc)
9138 		return rc;
9139 
9140 	memmove(buf + 4, iov[1].iov_base, buf_data_size);
9141 	*(__be32 *)buf = cpu_to_be32(buf_data_size);
9142 
9143 	return rc;
9144 }
9145 
9146 bool smb3_11_final_sess_setup_resp(struct ksmbd_work *work)
9147 {
9148 	struct ksmbd_conn *conn = work->conn;
9149 	struct ksmbd_session *sess = work->sess;
9150 	struct smb2_hdr *rsp = smb_get_msg(work->response_buf);
9151 
9152 	if (conn->dialect < SMB30_PROT_ID)
9153 		return false;
9154 
9155 	if (work->next_smb2_rcv_hdr_off)
9156 		rsp = ksmbd_resp_buf_next(work);
9157 
9158 	if (le16_to_cpu(rsp->Command) == SMB2_SESSION_SETUP_HE &&
9159 	    sess->user && !user_guest(sess->user) &&
9160 	    rsp->Status == STATUS_SUCCESS)
9161 		return true;
9162 	return false;
9163 }
9164