1 // SPDX-License-Identifier: LGPL-2.1
4 * Copyright (C) International Business Machines Corp., 2002,2011
10 #include <linux/string.h>
11 #include <linux/sched/mm.h>
12 #include <linux/sched/signal.h>
13 #include <linux/list.h>
14 #include <linux/wait.h>
15 #include <linux/slab.h>
16 #include <linux/pagemap.h>
17 #include <linux/ctype.h>
18 #include <linux/utsname.h>
19 #include <linux/mempool.h>
20 #include <linux/delay.h>
21 #include <linux/completion.h>
22 #include <linux/kthread.h>
23 #include <linux/pagevec.h>
24 #include <linux/freezer.h>
25 #include <linux/namei.h>
26 #include <linux/uuid.h>
27 #include <linux/uaccess.h>
28 #include <asm/processor.h>
29 #include <linux/inet.h>
30 #include <linux/module.h>
31 #include <keys/user-type.h>
33 #include <linux/parser.h>
34 #include <linux/bvec.h>
37 #include "cifsproto.h"
38 #include "cifs_unicode.h"
39 #include "cifs_debug.h"
40 #include "cifs_fs_sb.h"
43 #include "rfc1002pdu.h"
45 #include "smb2proto.h"
46 #include "smbdirect.h"
47 #include "dns_resolve.h"
48 #ifdef CONFIG_CIFS_DFS_UPCALL
50 #include "dfs_cache.h"
52 #include "fs_context.h"
55 /* FIXME: should these be tunable? */
56 #define TLINK_ERROR_EXPIRE (1 * HZ)
57 #define TLINK_IDLE_EXPIRE (600 * HZ)
59 /* Drop the connection to not overload the server */
60 #define MAX_STATUS_IO_TIMEOUT 5
62 static int ip_connect(struct TCP_Server_Info *server);
63 static int generic_ip_connect(struct TCP_Server_Info *server);
64 static void tlink_rb_insert(struct rb_root *root, struct tcon_link *new_tlink);
65 static void cifs_prune_tlinks(struct work_struct *work);
68 * Resolve hostname and set ip addr in tcp ses. Useful for hostnames that may
69 * get their ip addresses changed at some point.
71 * This should be called with server->srv_mutex held.
73 static int reconn_set_ipaddr_from_hostname(struct TCP_Server_Info *server)
78 struct sockaddr_storage ss;
80 if (!server->hostname)
83 /* if server hostname isn't populated, there's nothing to do here */
84 if (server->hostname[0] == '\0')
87 len = strlen(server->hostname) + 3;
89 unc = kmalloc(len, GFP_KERNEL);
91 cifs_dbg(FYI, "%s: failed to create UNC path\n", __func__);
94 scnprintf(unc, len, "\\\\%s", server->hostname);
96 spin_lock(&server->srv_lock);
98 spin_unlock(&server->srv_lock);
100 rc = dns_resolve_server_name_to_ip(unc, (struct sockaddr *)&ss, NULL);
104 cifs_dbg(FYI, "%s: failed to resolve server part of %s to IP: %d\n",
105 __func__, server->hostname, rc);
107 spin_lock(&server->srv_lock);
108 memcpy(&server->dstaddr, &ss, sizeof(server->dstaddr));
109 spin_unlock(&server->srv_lock);
116 static void smb2_query_server_interfaces(struct work_struct *work)
120 struct cifs_tcon *tcon = container_of(work,
122 query_interfaces.work);
123 struct TCP_Server_Info *server = tcon->ses->server;
126 * query server network interfaces, in case they change
128 if (!server->ops->query_server_interfaces)
132 rc = server->ops->query_server_interfaces(xid, tcon, false);
136 if (rc == -EOPNOTSUPP)
139 cifs_dbg(FYI, "%s: failed to query server interfaces: %d\n",
143 queue_delayed_work(cifsiod_wq, &tcon->query_interfaces,
144 (SMB_INTERFACE_POLL_INTERVAL * HZ));
148 * Update the tcpStatus for the server.
149 * This is used to signal the cifsd thread to call cifs_reconnect
150 * ONLY cifsd thread should call cifs_reconnect. For any other
151 * thread, use this function
153 * @server: the tcp ses for which reconnect is needed
154 * @all_channels: if this needs to be done for all channels
157 cifs_signal_cifsd_for_reconnect(struct TCP_Server_Info *server,
160 struct TCP_Server_Info *pserver;
161 struct cifs_ses *ses;
164 /* If server is a channel, select the primary channel */
165 pserver = SERVER_IS_CHAN(server) ? server->primary_server : server;
167 /* if we need to signal just this channel */
169 spin_lock(&server->srv_lock);
170 if (server->tcpStatus != CifsExiting)
171 server->tcpStatus = CifsNeedReconnect;
172 spin_unlock(&server->srv_lock);
176 spin_lock(&cifs_tcp_ses_lock);
177 list_for_each_entry(ses, &pserver->smb_ses_list, smb_ses_list) {
178 if (cifs_ses_exiting(ses))
180 spin_lock(&ses->chan_lock);
181 for (i = 0; i < ses->chan_count; i++) {
182 if (!ses->chans[i].server)
185 spin_lock(&ses->chans[i].server->srv_lock);
186 if (ses->chans[i].server->tcpStatus != CifsExiting)
187 ses->chans[i].server->tcpStatus = CifsNeedReconnect;
188 spin_unlock(&ses->chans[i].server->srv_lock);
190 spin_unlock(&ses->chan_lock);
192 spin_unlock(&cifs_tcp_ses_lock);
196 * Mark all sessions and tcons for reconnect.
197 * IMPORTANT: make sure that this gets called only from
198 * cifsd thread. For any other thread, use
199 * cifs_signal_cifsd_for_reconnect
201 * @server: the tcp ses for which reconnect is needed
202 * @server needs to be previously set to CifsNeedReconnect.
203 * @mark_smb_session: whether even sessions need to be marked
206 cifs_mark_tcp_ses_conns_for_reconnect(struct TCP_Server_Info *server,
207 bool mark_smb_session)
209 struct TCP_Server_Info *pserver;
210 struct cifs_ses *ses, *nses;
211 struct cifs_tcon *tcon;
214 * before reconnecting the tcp session, mark the smb session (uid) and the tid bad so they
215 * are not used until reconnected.
217 cifs_dbg(FYI, "%s: marking necessary sessions and tcons for reconnect\n", __func__);
219 /* If server is a channel, select the primary channel */
220 pserver = SERVER_IS_CHAN(server) ? server->primary_server : server;
223 * if the server has been marked for termination, there is a
224 * chance that the remaining channels all need reconnect. To be
225 * on the safer side, mark the session and trees for reconnect
226 * for this scenario. This might cause a few redundant session
227 * setup and tree connect requests, but it is better than not doing
228 * a tree connect when needed, and all following requests failing
230 if (server->terminate) {
231 mark_smb_session = true;
235 spin_lock(&cifs_tcp_ses_lock);
236 list_for_each_entry_safe(ses, nses, &pserver->smb_ses_list, smb_ses_list) {
237 spin_lock(&ses->ses_lock);
238 if (ses->ses_status == SES_EXITING) {
239 spin_unlock(&ses->ses_lock);
242 spin_unlock(&ses->ses_lock);
244 spin_lock(&ses->chan_lock);
245 if (cifs_ses_get_chan_index(ses, server) ==
246 CIFS_INVAL_CHAN_INDEX) {
247 spin_unlock(&ses->chan_lock);
251 if (!cifs_chan_is_iface_active(ses, server)) {
252 spin_unlock(&ses->chan_lock);
253 cifs_chan_update_iface(ses, server);
254 spin_lock(&ses->chan_lock);
257 if (!mark_smb_session && cifs_chan_needs_reconnect(ses, server)) {
258 spin_unlock(&ses->chan_lock);
262 if (mark_smb_session)
263 CIFS_SET_ALL_CHANS_NEED_RECONNECT(ses);
265 cifs_chan_set_need_reconnect(ses, server);
267 cifs_dbg(FYI, "%s: channel connect bitmap: 0x%lx\n",
268 __func__, ses->chans_need_reconnect);
270 /* If all channels need reconnect, then tcon needs reconnect */
271 if (!mark_smb_session && !CIFS_ALL_CHANS_NEED_RECONNECT(ses)) {
272 spin_unlock(&ses->chan_lock);
275 spin_unlock(&ses->chan_lock);
277 spin_lock(&ses->ses_lock);
278 ses->ses_status = SES_NEED_RECON;
279 spin_unlock(&ses->ses_lock);
281 list_for_each_entry(tcon, &ses->tcon_list, tcon_list) {
282 tcon->need_reconnect = true;
283 spin_lock(&tcon->tc_lock);
284 tcon->status = TID_NEED_RECON;
285 spin_unlock(&tcon->tc_lock);
287 cancel_delayed_work(&tcon->query_interfaces);
290 ses->tcon_ipc->need_reconnect = true;
291 spin_lock(&ses->tcon_ipc->tc_lock);
292 ses->tcon_ipc->status = TID_NEED_RECON;
293 spin_unlock(&ses->tcon_ipc->tc_lock);
296 spin_unlock(&cifs_tcp_ses_lock);
300 cifs_abort_connection(struct TCP_Server_Info *server)
302 struct mid_q_entry *mid, *nmid;
303 struct list_head retry_list;
306 server->max_read = 0;
308 /* do not want to be sending data on a socket we are freeing */
309 cifs_dbg(FYI, "%s: tearing down socket\n", __func__);
310 cifs_server_lock(server);
311 if (server->ssocket) {
312 cifs_dbg(FYI, "State: 0x%x Flags: 0x%lx\n", server->ssocket->state,
313 server->ssocket->flags);
314 kernel_sock_shutdown(server->ssocket, SHUT_WR);
315 cifs_dbg(FYI, "Post shutdown state: 0x%x Flags: 0x%lx\n", server->ssocket->state,
316 server->ssocket->flags);
317 sock_release(server->ssocket);
318 server->ssocket = NULL;
320 server->sequence_number = 0;
321 server->session_estab = false;
322 kfree_sensitive(server->session_key.response);
323 server->session_key.response = NULL;
324 server->session_key.len = 0;
325 server->lstrp = jiffies;
327 /* mark submitted MIDs for retry and issue callback */
328 INIT_LIST_HEAD(&retry_list);
329 cifs_dbg(FYI, "%s: moving mids to private list\n", __func__);
330 spin_lock(&server->mid_lock);
331 list_for_each_entry_safe(mid, nmid, &server->pending_mid_q, qhead) {
332 kref_get(&mid->refcount);
333 if (mid->mid_state == MID_REQUEST_SUBMITTED)
334 mid->mid_state = MID_RETRY_NEEDED;
335 list_move(&mid->qhead, &retry_list);
336 mid->mid_flags |= MID_DELETED;
338 spin_unlock(&server->mid_lock);
339 cifs_server_unlock(server);
341 cifs_dbg(FYI, "%s: issuing mid callbacks\n", __func__);
342 list_for_each_entry_safe(mid, nmid, &retry_list, qhead) {
343 list_del_init(&mid->qhead);
348 if (cifs_rdma_enabled(server)) {
349 cifs_server_lock(server);
350 smbd_destroy(server);
351 cifs_server_unlock(server);
355 static bool cifs_tcp_ses_needs_reconnect(struct TCP_Server_Info *server, int num_targets)
357 spin_lock(&server->srv_lock);
358 server->nr_targets = num_targets;
359 if (server->tcpStatus == CifsExiting) {
360 /* the demux thread will exit normally next time through the loop */
361 spin_unlock(&server->srv_lock);
362 wake_up(&server->response_q);
366 cifs_dbg(FYI, "Mark tcp session as need reconnect\n");
367 trace_smb3_reconnect(server->CurrentMid, server->conn_id,
369 server->tcpStatus = CifsNeedReconnect;
371 spin_unlock(&server->srv_lock);
376 * cifs tcp session reconnection
378 * mark tcp session as reconnecting so temporarily locked
379 * mark all smb sessions as reconnecting for tcp session
380 * reconnect tcp session
381 * wake up waiters on reconnection? - (not needed currently)
383 * if mark_smb_session is passed as true, unconditionally mark
384 * the smb session (and tcon) for reconnect as well. This value
385 * doesn't really matter for non-multichannel scenario.
388 static int __cifs_reconnect(struct TCP_Server_Info *server,
389 bool mark_smb_session)
393 if (!cifs_tcp_ses_needs_reconnect(server, 1))
396 cifs_mark_tcp_ses_conns_for_reconnect(server, mark_smb_session);
398 cifs_abort_connection(server);
402 cifs_server_lock(server);
404 if (!cifs_swn_set_server_dstaddr(server)) {
405 /* resolve the hostname again to make sure that IP address is up-to-date */
406 rc = reconn_set_ipaddr_from_hostname(server);
407 cifs_dbg(FYI, "%s: reconn_set_ipaddr_from_hostname: rc=%d\n", __func__, rc);
410 if (cifs_rdma_enabled(server))
411 rc = smbd_reconnect(server);
413 rc = generic_ip_connect(server);
415 cifs_server_unlock(server);
416 cifs_dbg(FYI, "%s: reconnect error %d\n", __func__, rc);
419 atomic_inc(&tcpSesReconnectCount);
420 set_credits(server, 1);
421 spin_lock(&server->srv_lock);
422 if (server->tcpStatus != CifsExiting)
423 server->tcpStatus = CifsNeedNegotiate;
424 spin_unlock(&server->srv_lock);
425 cifs_swn_reset_server_dstaddr(server);
426 cifs_server_unlock(server);
427 mod_delayed_work(cifsiod_wq, &server->reconnect, 0);
429 } while (server->tcpStatus == CifsNeedReconnect);
431 spin_lock(&server->srv_lock);
432 if (server->tcpStatus == CifsNeedNegotiate)
433 mod_delayed_work(cifsiod_wq, &server->echo, 0);
434 spin_unlock(&server->srv_lock);
436 wake_up(&server->response_q);
440 #ifdef CONFIG_CIFS_DFS_UPCALL
441 static int __reconnect_target_unlocked(struct TCP_Server_Info *server, const char *target)
446 if (!cifs_swn_set_server_dstaddr(server)) {
447 if (server->hostname != target) {
448 hostname = extract_hostname(target);
449 if (!IS_ERR(hostname)) {
450 spin_lock(&server->srv_lock);
451 kfree(server->hostname);
452 server->hostname = hostname;
453 spin_unlock(&server->srv_lock);
455 cifs_dbg(FYI, "%s: couldn't extract hostname or address from dfs target: %ld\n",
456 __func__, PTR_ERR(hostname));
457 cifs_dbg(FYI, "%s: default to last target server: %s\n", __func__,
461 /* resolve the hostname again to make sure that IP address is up-to-date. */
462 rc = reconn_set_ipaddr_from_hostname(server);
463 cifs_dbg(FYI, "%s: reconn_set_ipaddr_from_hostname: rc=%d\n", __func__, rc);
465 /* Reconnect the socket */
466 if (cifs_rdma_enabled(server))
467 rc = smbd_reconnect(server);
469 rc = generic_ip_connect(server);
474 static int reconnect_target_unlocked(struct TCP_Server_Info *server, struct dfs_cache_tgt_list *tl,
475 struct dfs_cache_tgt_iterator **target_hint)
478 struct dfs_cache_tgt_iterator *tit;
482 /* If dfs target list is empty, then reconnect to last server */
483 tit = dfs_cache_get_tgt_iterator(tl);
485 return __reconnect_target_unlocked(server, server->hostname);
487 /* Otherwise, try every dfs target in @tl */
488 for (; tit; tit = dfs_cache_get_next_tgt(tl, tit)) {
489 rc = __reconnect_target_unlocked(server, dfs_cache_get_tgt_name(tit));
498 static int reconnect_dfs_server(struct TCP_Server_Info *server)
500 struct dfs_cache_tgt_iterator *target_hint = NULL;
502 DFS_CACHE_TGT_LIST(tl);
507 * Determine the number of dfs targets the referral path in @cifs_sb resolves to.
509 * smb2_reconnect() needs to know how long it should wait based upon the number of dfs
510 * targets (server->nr_targets). It's also possible that the cached referral was cleared
511 * through /proc/fs/cifs/dfscache or the target list is empty due to server settings after
512 * refreshing the referral, so, in this case, default it to 1.
514 mutex_lock(&server->refpath_lock);
515 if (!dfs_cache_noreq_find(server->leaf_fullpath + 1, NULL, &tl))
516 num_targets = dfs_cache_get_nr_tgts(&tl);
517 mutex_unlock(&server->refpath_lock);
521 if (!cifs_tcp_ses_needs_reconnect(server, num_targets))
525 * Unconditionally mark all sessions & tcons for reconnect as we might be connecting to a
526 * different server or share during failover. It could be improved by adding some logic to
527 * only do that in case it connects to a different server or share, though.
529 cifs_mark_tcp_ses_conns_for_reconnect(server, true);
531 cifs_abort_connection(server);
535 cifs_server_lock(server);
537 rc = reconnect_target_unlocked(server, &tl, &target_hint);
539 /* Failed to reconnect socket */
540 cifs_server_unlock(server);
541 cifs_dbg(FYI, "%s: reconnect error %d\n", __func__, rc);
546 * Socket was created. Update tcp session status to CifsNeedNegotiate so that a
547 * process waiting for reconnect will know it needs to re-establish session and tcon
548 * through the reconnected target server.
550 atomic_inc(&tcpSesReconnectCount);
551 set_credits(server, 1);
552 spin_lock(&server->srv_lock);
553 if (server->tcpStatus != CifsExiting)
554 server->tcpStatus = CifsNeedNegotiate;
555 spin_unlock(&server->srv_lock);
556 cifs_swn_reset_server_dstaddr(server);
557 cifs_server_unlock(server);
558 mod_delayed_work(cifsiod_wq, &server->reconnect, 0);
559 } while (server->tcpStatus == CifsNeedReconnect);
561 mutex_lock(&server->refpath_lock);
562 dfs_cache_noreq_update_tgthint(server->leaf_fullpath + 1, target_hint);
563 mutex_unlock(&server->refpath_lock);
564 dfs_cache_free_tgts(&tl);
566 /* Need to set up echo worker again once connection has been established */
567 spin_lock(&server->srv_lock);
568 if (server->tcpStatus == CifsNeedNegotiate)
569 mod_delayed_work(cifsiod_wq, &server->echo, 0);
570 spin_unlock(&server->srv_lock);
572 wake_up(&server->response_q);
576 int cifs_reconnect(struct TCP_Server_Info *server, bool mark_smb_session)
578 mutex_lock(&server->refpath_lock);
579 if (!server->leaf_fullpath) {
580 mutex_unlock(&server->refpath_lock);
581 return __cifs_reconnect(server, mark_smb_session);
583 mutex_unlock(&server->refpath_lock);
585 return reconnect_dfs_server(server);
588 int cifs_reconnect(struct TCP_Server_Info *server, bool mark_smb_session)
590 return __cifs_reconnect(server, mark_smb_session);
595 cifs_echo_request(struct work_struct *work)
598 struct TCP_Server_Info *server = container_of(work,
599 struct TCP_Server_Info, echo.work);
602 * We cannot send an echo if it is disabled.
603 * Also, no need to ping if we got a response recently.
606 if (server->tcpStatus == CifsNeedReconnect ||
607 server->tcpStatus == CifsExiting ||
608 server->tcpStatus == CifsNew ||
609 (server->ops->can_echo && !server->ops->can_echo(server)) ||
610 time_before(jiffies, server->lstrp + server->echo_interval - HZ))
613 rc = server->ops->echo ? server->ops->echo(server) : -ENOSYS;
614 cifs_server_dbg(FYI, "send echo request: rc = %d\n", rc);
616 /* Check witness registrations */
620 queue_delayed_work(cifsiod_wq, &server->echo, server->echo_interval);
624 allocate_buffers(struct TCP_Server_Info *server)
626 if (!server->bigbuf) {
627 server->bigbuf = (char *)cifs_buf_get();
628 if (!server->bigbuf) {
629 cifs_server_dbg(VFS, "No memory for large SMB response\n");
631 /* retry will check if exiting */
634 } else if (server->large_buf) {
635 /* we are reusing a dirty large buf, clear its start */
636 memset(server->bigbuf, 0, HEADER_SIZE(server));
639 if (!server->smallbuf) {
640 server->smallbuf = (char *)cifs_small_buf_get();
641 if (!server->smallbuf) {
642 cifs_server_dbg(VFS, "No memory for SMB response\n");
644 /* retry will check if exiting */
647 /* beginning of smb buffer is cleared in our buf_get */
649 /* if existing small buf clear beginning */
650 memset(server->smallbuf, 0, HEADER_SIZE(server));
657 server_unresponsive(struct TCP_Server_Info *server)
660 * If we're in the process of mounting a share or reconnecting a session
661 * and the server abruptly shut down (e.g. socket wasn't closed, packet
662 * had been ACK'ed but no SMB response), don't wait longer than 20s to
663 * negotiate protocol.
665 spin_lock(&server->srv_lock);
666 if (server->tcpStatus == CifsInNegotiate &&
667 time_after(jiffies, server->lstrp + 20 * HZ)) {
668 spin_unlock(&server->srv_lock);
669 cifs_reconnect(server, false);
673 * We need to wait 3 echo intervals to make sure we handle such
675 * 1s client sends a normal SMB request
676 * 2s client gets a response
677 * 30s echo workqueue job pops, and decides we got a response recently
678 * and don't need to send another
680 * 65s kernel_recvmsg times out, and we see that we haven't gotten
681 * a response in >60s.
683 if ((server->tcpStatus == CifsGood ||
684 server->tcpStatus == CifsNeedNegotiate) &&
685 (!server->ops->can_echo || server->ops->can_echo(server)) &&
686 time_after(jiffies, server->lstrp + 3 * server->echo_interval)) {
687 spin_unlock(&server->srv_lock);
688 cifs_server_dbg(VFS, "has not responded in %lu seconds. Reconnecting...\n",
689 (3 * server->echo_interval) / HZ);
690 cifs_reconnect(server, false);
693 spin_unlock(&server->srv_lock);
699 zero_credits(struct TCP_Server_Info *server)
703 spin_lock(&server->req_lock);
704 val = server->credits + server->echo_credits + server->oplock_credits;
705 if (server->in_flight == 0 && val == 0) {
706 spin_unlock(&server->req_lock);
709 spin_unlock(&server->req_lock);
714 cifs_readv_from_socket(struct TCP_Server_Info *server, struct msghdr *smb_msg)
719 for (total_read = 0; msg_data_left(smb_msg); total_read += length) {
722 /* reconnect if no credits and no requests in flight */
723 if (zero_credits(server)) {
724 cifs_reconnect(server, false);
725 return -ECONNABORTED;
728 if (server_unresponsive(server))
729 return -ECONNABORTED;
730 if (cifs_rdma_enabled(server) && server->smbd_conn)
731 length = smbd_recv(server->smbd_conn, smb_msg);
733 length = sock_recvmsg(server->ssocket, smb_msg, 0);
735 spin_lock(&server->srv_lock);
736 if (server->tcpStatus == CifsExiting) {
737 spin_unlock(&server->srv_lock);
741 if (server->tcpStatus == CifsNeedReconnect) {
742 spin_unlock(&server->srv_lock);
743 cifs_reconnect(server, false);
744 return -ECONNABORTED;
746 spin_unlock(&server->srv_lock);
748 if (length == -ERESTARTSYS ||
752 * Minimum sleep to prevent looping, allowing socket
753 * to clear and app threads to set tcpStatus
754 * CifsNeedReconnect if server hung.
756 usleep_range(1000, 2000);
762 cifs_dbg(FYI, "Received no data or error: %d\n", length);
763 cifs_reconnect(server, false);
764 return -ECONNABORTED;
771 cifs_read_from_socket(struct TCP_Server_Info *server, char *buf,
772 unsigned int to_read)
774 struct msghdr smb_msg = {};
775 struct kvec iov = {.iov_base = buf, .iov_len = to_read};
777 iov_iter_kvec(&smb_msg.msg_iter, ITER_DEST, &iov, 1, to_read);
779 return cifs_readv_from_socket(server, &smb_msg);
783 cifs_discard_from_socket(struct TCP_Server_Info *server, size_t to_read)
785 struct msghdr smb_msg = {};
788 * iov_iter_discard already sets smb_msg.type and count and iov_offset
789 * and cifs_readv_from_socket sets msg_control and msg_controllen
790 * so little to initialize in struct msghdr
792 iov_iter_discard(&smb_msg.msg_iter, ITER_DEST, to_read);
794 return cifs_readv_from_socket(server, &smb_msg);
798 cifs_read_iter_from_socket(struct TCP_Server_Info *server, struct iov_iter *iter,
799 unsigned int to_read)
801 struct msghdr smb_msg = { .msg_iter = *iter };
803 iov_iter_truncate(&smb_msg.msg_iter, to_read);
804 return cifs_readv_from_socket(server, &smb_msg);
808 is_smb_response(struct TCP_Server_Info *server, unsigned char type)
811 * The first byte big endian of the length field,
812 * is actually not part of the length but the type
813 * with the most common, zero, as regular data.
816 case RFC1002_SESSION_MESSAGE:
817 /* Regular SMB response */
819 case RFC1002_SESSION_KEEP_ALIVE:
820 cifs_dbg(FYI, "RFC 1002 session keep alive\n");
822 case RFC1002_POSITIVE_SESSION_RESPONSE:
823 cifs_dbg(FYI, "RFC 1002 positive session response\n");
825 case RFC1002_NEGATIVE_SESSION_RESPONSE:
827 * We get this from Windows 98 instead of an error on
828 * SMB negprot response.
830 cifs_dbg(FYI, "RFC 1002 negative session response\n");
831 /* give server a second to clean up */
834 * Always try 445 first on reconnect since we get NACK
835 * on some if we ever connected to port 139 (the NACK
836 * is since we do not begin with RFC1001 session
839 cifs_set_port((struct sockaddr *)&server->dstaddr, CIFS_PORT);
840 cifs_reconnect(server, true);
843 cifs_server_dbg(VFS, "RFC 1002 unknown response type 0x%x\n", type);
844 cifs_reconnect(server, true);
851 dequeue_mid(struct mid_q_entry *mid, bool malformed)
853 #ifdef CONFIG_CIFS_STATS2
854 mid->when_received = jiffies;
856 spin_lock(&mid->server->mid_lock);
858 mid->mid_state = MID_RESPONSE_RECEIVED;
860 mid->mid_state = MID_RESPONSE_MALFORMED;
862 * Trying to handle/dequeue a mid after the send_recv()
863 * function has finished processing it is a bug.
865 if (mid->mid_flags & MID_DELETED) {
866 spin_unlock(&mid->server->mid_lock);
867 pr_warn_once("trying to dequeue a deleted mid\n");
869 list_del_init(&mid->qhead);
870 mid->mid_flags |= MID_DELETED;
871 spin_unlock(&mid->server->mid_lock);
876 smb2_get_credits_from_hdr(char *buffer, struct TCP_Server_Info *server)
878 struct smb2_hdr *shdr = (struct smb2_hdr *)buffer;
881 * SMB1 does not use credits.
886 return le16_to_cpu(shdr->CreditRequest);
890 handle_mid(struct mid_q_entry *mid, struct TCP_Server_Info *server,
891 char *buf, int malformed)
893 if (server->ops->check_trans2 &&
894 server->ops->check_trans2(mid, server, buf, malformed))
896 mid->credits_received = smb2_get_credits_from_hdr(buf, server);
898 mid->large_buf = server->large_buf;
899 /* Was previous buf put in mpx struct for multi-rsp? */
900 if (!mid->multiRsp) {
901 /* smb buffer will be freed by user thread */
902 if (server->large_buf)
903 server->bigbuf = NULL;
905 server->smallbuf = NULL;
907 dequeue_mid(mid, malformed);
911 cifs_enable_signing(struct TCP_Server_Info *server, bool mnt_sign_required)
913 bool srv_sign_required = server->sec_mode & server->vals->signing_required;
914 bool srv_sign_enabled = server->sec_mode & server->vals->signing_enabled;
915 bool mnt_sign_enabled;
918 * Is signing required by mnt options? If not then check
919 * global_secflags to see if it is there.
921 if (!mnt_sign_required)
922 mnt_sign_required = ((global_secflags & CIFSSEC_MUST_SIGN) ==
926 * If signing is required then it's automatically enabled too,
927 * otherwise, check to see if the secflags allow it.
929 mnt_sign_enabled = mnt_sign_required ? mnt_sign_required :
930 (global_secflags & CIFSSEC_MAY_SIGN);
932 /* If server requires signing, does client allow it? */
933 if (srv_sign_required) {
934 if (!mnt_sign_enabled) {
935 cifs_dbg(VFS, "Server requires signing, but it's disabled in SecurityFlags!\n");
941 /* If client requires signing, does server allow it? */
942 if (mnt_sign_required) {
943 if (!srv_sign_enabled) {
944 cifs_dbg(VFS, "Server does not support signing!\n");
950 if (cifs_rdma_enabled(server) && server->sign)
951 cifs_dbg(VFS, "Signing is enabled, and RDMA read/write will be disabled\n");
956 static noinline_for_stack void
957 clean_demultiplex_info(struct TCP_Server_Info *server)
961 /* take it off the list, if it's not already */
962 spin_lock(&server->srv_lock);
963 list_del_init(&server->tcp_ses_list);
964 spin_unlock(&server->srv_lock);
966 cancel_delayed_work_sync(&server->echo);
968 spin_lock(&server->srv_lock);
969 server->tcpStatus = CifsExiting;
970 spin_unlock(&server->srv_lock);
971 wake_up_all(&server->response_q);
973 /* check if we have blocked requests that need to free */
974 spin_lock(&server->req_lock);
975 if (server->credits <= 0)
977 spin_unlock(&server->req_lock);
979 * Although there should not be any requests blocked on this queue it
980 * can not hurt to be paranoid and try to wake up requests that may
981 * haven been blocked when more than 50 at time were on the wire to the
982 * same server - they now will see the session is in exit state and get
983 * out of SendReceive.
985 wake_up_all(&server->request_q);
986 /* give those requests time to exit */
988 if (cifs_rdma_enabled(server))
989 smbd_destroy(server);
991 if (server->ssocket) {
992 sock_release(server->ssocket);
993 server->ssocket = NULL;
995 /* Release netns reference for the socket. */
996 put_net(cifs_net_ns(server));
999 if (!list_empty(&server->pending_mid_q)) {
1000 struct mid_q_entry *mid_entry;
1001 struct list_head *tmp, *tmp2;
1002 LIST_HEAD(dispose_list);
1004 spin_lock(&server->mid_lock);
1005 list_for_each_safe(tmp, tmp2, &server->pending_mid_q) {
1006 mid_entry = list_entry(tmp, struct mid_q_entry, qhead);
1007 cifs_dbg(FYI, "Clearing mid %llu\n", mid_entry->mid);
1008 kref_get(&mid_entry->refcount);
1009 mid_entry->mid_state = MID_SHUTDOWN;
1010 list_move(&mid_entry->qhead, &dispose_list);
1011 mid_entry->mid_flags |= MID_DELETED;
1013 spin_unlock(&server->mid_lock);
1015 /* now walk dispose list and issue callbacks */
1016 list_for_each_safe(tmp, tmp2, &dispose_list) {
1017 mid_entry = list_entry(tmp, struct mid_q_entry, qhead);
1018 cifs_dbg(FYI, "Callback mid %llu\n", mid_entry->mid);
1019 list_del_init(&mid_entry->qhead);
1020 mid_entry->callback(mid_entry);
1021 release_mid(mid_entry);
1023 /* 1/8th of sec is more than enough time for them to exit */
1027 if (!list_empty(&server->pending_mid_q)) {
1029 * mpx threads have not exited yet give them at least the smb
1030 * send timeout time for long ops.
1032 * Due to delays on oplock break requests, we need to wait at
1033 * least 45 seconds before giving up on a request getting a
1034 * response and going ahead and killing cifsd.
1036 cifs_dbg(FYI, "Wait for exit from demultiplex thread\n");
1039 * If threads still have not exited they are probably never
1040 * coming home not much else we can do but free the memory.
1044 /* Release netns reference for this server. */
1045 put_net(cifs_net_ns(server));
1046 kfree(server->leaf_fullpath);
1049 length = atomic_dec_return(&tcpSesAllocCount);
1051 mempool_resize(cifs_req_poolp, length + cifs_min_rcv);
1055 standard_receive3(struct TCP_Server_Info *server, struct mid_q_entry *mid)
1058 char *buf = server->smallbuf;
1059 unsigned int pdu_length = server->pdu_size;
1061 /* make sure this will fit in a large buffer */
1062 if (pdu_length > CIFSMaxBufSize + MAX_HEADER_SIZE(server) -
1063 HEADER_PREAMBLE_SIZE(server)) {
1064 cifs_server_dbg(VFS, "SMB response too long (%u bytes)\n", pdu_length);
1065 cifs_reconnect(server, true);
1066 return -ECONNABORTED;
1069 /* switch to large buffer if too big for a small one */
1070 if (pdu_length > MAX_CIFS_SMALL_BUFFER_SIZE - 4) {
1071 server->large_buf = true;
1072 memcpy(server->bigbuf, buf, server->total_read);
1073 buf = server->bigbuf;
1076 /* now read the rest */
1077 length = cifs_read_from_socket(server, buf + HEADER_SIZE(server) - 1,
1078 pdu_length - MID_HEADER_SIZE(server));
1082 server->total_read += length;
1084 dump_smb(buf, server->total_read);
1086 return cifs_handle_standard(server, mid);
1090 cifs_handle_standard(struct TCP_Server_Info *server, struct mid_q_entry *mid)
1092 char *buf = server->large_buf ? server->bigbuf : server->smallbuf;
1096 * We know that we received enough to get to the MID as we
1097 * checked the pdu_length earlier. Now check to see
1098 * if the rest of the header is OK.
1100 * 48 bytes is enough to display the header and a little bit
1101 * into the payload for debugging purposes.
1103 rc = server->ops->check_message(buf, server->total_read, server);
1105 cifs_dump_mem("Bad SMB: ", buf,
1106 min_t(unsigned int, server->total_read, 48));
1108 if (server->ops->is_session_expired &&
1109 server->ops->is_session_expired(buf)) {
1110 cifs_reconnect(server, true);
1114 if (server->ops->is_status_pending &&
1115 server->ops->is_status_pending(buf, server))
1121 handle_mid(mid, server, buf, rc);
1126 smb2_add_credits_from_hdr(char *buffer, struct TCP_Server_Info *server)
1128 struct smb2_hdr *shdr = (struct smb2_hdr *)buffer;
1129 int scredits, in_flight;
1132 * SMB1 does not use credits.
1134 if (is_smb1(server))
1137 if (shdr->CreditRequest) {
1138 spin_lock(&server->req_lock);
1139 server->credits += le16_to_cpu(shdr->CreditRequest);
1140 scredits = server->credits;
1141 in_flight = server->in_flight;
1142 spin_unlock(&server->req_lock);
1143 wake_up(&server->request_q);
1145 trace_smb3_hdr_credits(server->CurrentMid,
1146 server->conn_id, server->hostname, scredits,
1147 le16_to_cpu(shdr->CreditRequest), in_flight);
1148 cifs_server_dbg(FYI, "%s: added %u credits total=%d\n",
1149 __func__, le16_to_cpu(shdr->CreditRequest),
1156 cifs_demultiplex_thread(void *p)
1158 int i, num_mids, length;
1159 struct TCP_Server_Info *server = p;
1160 unsigned int pdu_length;
1161 unsigned int next_offset;
1163 struct task_struct *task_to_wake = NULL;
1164 struct mid_q_entry *mids[MAX_COMPOUND];
1165 char *bufs[MAX_COMPOUND];
1166 unsigned int noreclaim_flag, num_io_timeout = 0;
1167 bool pending_reconnect = false;
1169 noreclaim_flag = memalloc_noreclaim_save();
1170 cifs_dbg(FYI, "Demultiplex PID: %d\n", task_pid_nr(current));
1172 length = atomic_inc_return(&tcpSesAllocCount);
1174 mempool_resize(cifs_req_poolp, length + cifs_min_rcv);
1177 allow_kernel_signal(SIGKILL);
1178 while (server->tcpStatus != CifsExiting) {
1179 if (try_to_freeze())
1182 if (!allocate_buffers(server))
1185 server->large_buf = false;
1186 buf = server->smallbuf;
1187 pdu_length = 4; /* enough to get RFC1001 header */
1189 length = cifs_read_from_socket(server, buf, pdu_length);
1193 if (is_smb1(server))
1194 server->total_read = length;
1196 server->total_read = 0;
1199 * The right amount was read from socket - 4 bytes,
1200 * so we can now interpret the length field.
1202 pdu_length = get_rfc1002_length(buf);
1204 cifs_dbg(FYI, "RFC1002 header 0x%x\n", pdu_length);
1205 if (!is_smb_response(server, buf[0]))
1208 pending_reconnect = false;
1210 server->pdu_size = pdu_length;
1212 /* make sure we have enough to get to the MID */
1213 if (server->pdu_size < MID_HEADER_SIZE(server)) {
1214 cifs_server_dbg(VFS, "SMB response too short (%u bytes)\n",
1216 cifs_reconnect(server, true);
1220 /* read down to the MID */
1221 length = cifs_read_from_socket(server,
1222 buf + HEADER_PREAMBLE_SIZE(server),
1223 MID_HEADER_SIZE(server));
1226 server->total_read += length;
1228 if (server->ops->next_header) {
1229 if (server->ops->next_header(server, buf, &next_offset)) {
1230 cifs_dbg(VFS, "%s: malformed response (next_offset=%u)\n",
1231 __func__, next_offset);
1232 cifs_reconnect(server, true);
1236 server->pdu_size = next_offset;
1239 memset(mids, 0, sizeof(mids));
1240 memset(bufs, 0, sizeof(bufs));
1243 if (server->ops->is_transform_hdr &&
1244 server->ops->receive_transform &&
1245 server->ops->is_transform_hdr(buf)) {
1246 length = server->ops->receive_transform(server,
1251 mids[0] = server->ops->find_mid(server, buf);
1255 if (!mids[0] || !mids[0]->receive)
1256 length = standard_receive3(server, mids[0]);
1258 length = mids[0]->receive(server, mids[0]);
1262 for (i = 0; i < num_mids; i++)
1264 release_mid(mids[i]);
1268 if (server->ops->is_status_io_timeout &&
1269 server->ops->is_status_io_timeout(buf)) {
1271 if (num_io_timeout > MAX_STATUS_IO_TIMEOUT) {
1272 cifs_server_dbg(VFS,
1273 "Number of request timeouts exceeded %d. Reconnecting",
1274 MAX_STATUS_IO_TIMEOUT);
1276 pending_reconnect = true;
1281 server->lstrp = jiffies;
1283 for (i = 0; i < num_mids; i++) {
1284 if (mids[i] != NULL) {
1285 mids[i]->resp_buf_size = server->pdu_size;
1287 if (bufs[i] != NULL) {
1288 if (server->ops->is_network_name_deleted &&
1289 server->ops->is_network_name_deleted(bufs[i],
1291 cifs_server_dbg(FYI,
1292 "Share deleted. Reconnect needed");
1296 if (!mids[i]->multiRsp || mids[i]->multiEnd)
1297 mids[i]->callback(mids[i]);
1299 release_mid(mids[i]);
1300 } else if (server->ops->is_oplock_break &&
1301 server->ops->is_oplock_break(bufs[i],
1303 smb2_add_credits_from_hdr(bufs[i], server);
1304 cifs_dbg(FYI, "Received oplock break\n");
1306 cifs_server_dbg(VFS, "No task to wake, unknown frame received! NumMids %d\n",
1307 atomic_read(&mid_count));
1308 cifs_dump_mem("Received Data is: ", bufs[i],
1309 HEADER_SIZE(server));
1310 smb2_add_credits_from_hdr(bufs[i], server);
1311 #ifdef CONFIG_CIFS_DEBUG2
1312 if (server->ops->dump_detail)
1313 server->ops->dump_detail(bufs[i],
1315 cifs_dump_mids(server);
1316 #endif /* CIFS_DEBUG2 */
1320 if (pdu_length > server->pdu_size) {
1321 if (!allocate_buffers(server))
1323 pdu_length -= server->pdu_size;
1324 server->total_read = 0;
1325 server->large_buf = false;
1326 buf = server->smallbuf;
1330 /* do this reconnect at the very end after processing all MIDs */
1331 if (pending_reconnect)
1332 cifs_reconnect(server, true);
1334 } /* end while !EXITING */
1336 /* buffer usually freed in free_mid - need to free it here on exit */
1337 cifs_buf_release(server->bigbuf);
1338 if (server->smallbuf) /* no sense logging a debug message if NULL */
1339 cifs_small_buf_release(server->smallbuf);
1341 task_to_wake = xchg(&server->tsk, NULL);
1342 clean_demultiplex_info(server);
1344 /* if server->tsk was NULL then wait for a signal before exiting */
1345 if (!task_to_wake) {
1346 set_current_state(TASK_INTERRUPTIBLE);
1347 while (!signal_pending(current)) {
1349 set_current_state(TASK_INTERRUPTIBLE);
1351 set_current_state(TASK_RUNNING);
1354 memalloc_noreclaim_restore(noreclaim_flag);
1355 module_put_and_kthread_exit(0);
1359 cifs_ipaddr_cmp(struct sockaddr *srcaddr, struct sockaddr *rhs)
1361 struct sockaddr_in *saddr4 = (struct sockaddr_in *)srcaddr;
1362 struct sockaddr_in *vaddr4 = (struct sockaddr_in *)rhs;
1363 struct sockaddr_in6 *saddr6 = (struct sockaddr_in6 *)srcaddr;
1364 struct sockaddr_in6 *vaddr6 = (struct sockaddr_in6 *)rhs;
1366 switch (srcaddr->sa_family) {
1368 switch (rhs->sa_family) {
1378 switch (rhs->sa_family) {
1382 return memcmp(saddr4, vaddr4,
1383 sizeof(struct sockaddr_in));
1391 switch (rhs->sa_family) {
1396 return memcmp(saddr6,
1398 sizeof(struct sockaddr_in6));
1404 return -1; /* don't expect to be here */
1409 * Returns true if srcaddr isn't specified and rhs isn't specified, or
1410 * if srcaddr is specified and matches the IP address of the rhs argument
1413 cifs_match_ipaddr(struct sockaddr *srcaddr, struct sockaddr *rhs)
1415 switch (srcaddr->sa_family) {
1417 return (rhs->sa_family == AF_UNSPEC);
1419 struct sockaddr_in *saddr4 = (struct sockaddr_in *)srcaddr;
1420 struct sockaddr_in *vaddr4 = (struct sockaddr_in *)rhs;
1422 return (saddr4->sin_addr.s_addr == vaddr4->sin_addr.s_addr);
1425 struct sockaddr_in6 *saddr6 = (struct sockaddr_in6 *)srcaddr;
1426 struct sockaddr_in6 *vaddr6 = (struct sockaddr_in6 *)rhs;
1428 return (ipv6_addr_equal(&saddr6->sin6_addr, &vaddr6->sin6_addr)
1429 && saddr6->sin6_scope_id == vaddr6->sin6_scope_id);
1433 return false; /* don't expect to be here */
1438 * If no port is specified in addr structure, we try to match with 445 port
1439 * and if it fails - with 139 ports. It should be called only if address
1440 * families of server and addr are equal.
1443 match_port(struct TCP_Server_Info *server, struct sockaddr *addr)
1445 __be16 port, *sport;
1447 /* SMBDirect manages its own ports, don't match it here */
1451 switch (addr->sa_family) {
1453 sport = &((struct sockaddr_in *) &server->dstaddr)->sin_port;
1454 port = ((struct sockaddr_in *) addr)->sin_port;
1457 sport = &((struct sockaddr_in6 *) &server->dstaddr)->sin6_port;
1458 port = ((struct sockaddr_in6 *) addr)->sin6_port;
1466 port = htons(CIFS_PORT);
1470 port = htons(RFC1001_PORT);
1473 return port == *sport;
1476 static bool match_server_address(struct TCP_Server_Info *server, struct sockaddr *addr)
1478 if (!cifs_match_ipaddr(addr, (struct sockaddr *)&server->dstaddr))
1485 match_security(struct TCP_Server_Info *server, struct smb3_fs_context *ctx)
1488 * The select_sectype function should either return the ctx->sectype
1489 * that was specified, or "Unspecified" if that sectype was not
1490 * compatible with the given NEGOTIATE request.
1492 if (server->ops->select_sectype(server, ctx->sectype)
1497 * Now check if signing mode is acceptable. No need to check
1498 * global_secflags at this point since if MUST_SIGN is set then
1499 * the server->sign had better be too.
1501 if (ctx->sign && !server->sign)
1507 /* this function must be called with srv_lock held */
1508 static int match_server(struct TCP_Server_Info *server,
1509 struct smb3_fs_context *ctx,
1512 struct sockaddr *addr = (struct sockaddr *)&ctx->dstaddr;
1514 lockdep_assert_held(&server->srv_lock);
1516 if (ctx->nosharesock)
1519 /* this server does not share socket */
1520 if (server->nosharesock)
1523 if (!match_super && (ctx->dfs_conn || server->dfs_conn))
1526 /* If multidialect negotiation see if existing sessions match one */
1527 if (strcmp(ctx->vals->version_string, SMB3ANY_VERSION_STRING) == 0) {
1528 if (server->vals->protocol_id < SMB30_PROT_ID)
1530 } else if (strcmp(ctx->vals->version_string,
1531 SMBDEFAULT_VERSION_STRING) == 0) {
1532 if (server->vals->protocol_id < SMB21_PROT_ID)
1534 } else if ((server->vals != ctx->vals) || (server->ops != ctx->ops))
1537 if (!net_eq(cifs_net_ns(server), current->nsproxy->net_ns))
1540 if (!cifs_match_ipaddr((struct sockaddr *)&ctx->srcaddr,
1541 (struct sockaddr *)&server->srcaddr))
1544 * When matching cifs.ko superblocks (@match_super == true), we can't
1545 * really match either @server->leaf_fullpath or @server->dstaddr
1546 * directly since this @server might belong to a completely different
1547 * server -- in case of domain-based DFS referrals or DFS links -- as
1548 * provided earlier by mount(2) through 'source' and 'ip' options.
1550 * Otherwise, match the DFS referral in @server->leaf_fullpath or the
1551 * destination address in @server->dstaddr.
1553 * When using 'nodfs' mount option, we avoid sharing it with DFS
1554 * connections as they might failover.
1558 if (server->leaf_fullpath) {
1559 if (!ctx->leaf_fullpath ||
1560 strcasecmp(server->leaf_fullpath,
1561 ctx->leaf_fullpath))
1563 } else if (ctx->leaf_fullpath) {
1566 } else if (server->leaf_fullpath) {
1572 * Match for a regular connection (address/hostname/port) which has no
1573 * DFS referrals set.
1575 if (!server->leaf_fullpath &&
1576 (strcasecmp(server->hostname, ctx->server_hostname) ||
1577 !match_server_address(server, addr) ||
1578 !match_port(server, addr)))
1581 if (!match_security(server, ctx))
1584 if (server->echo_interval != ctx->echo_interval * HZ)
1587 if (server->rdma != ctx->rdma)
1590 if (server->ignore_signature != ctx->ignore_signature)
1593 if (server->min_offload != ctx->min_offload)
1596 if (server->retrans != ctx->retrans)
1602 struct TCP_Server_Info *
1603 cifs_find_tcp_session(struct smb3_fs_context *ctx)
1605 struct TCP_Server_Info *server;
1607 spin_lock(&cifs_tcp_ses_lock);
1608 list_for_each_entry(server, &cifs_tcp_ses_list, tcp_ses_list) {
1609 spin_lock(&server->srv_lock);
1611 * Skip ses channels since they're only handled in lower layers
1612 * (e.g. cifs_send_recv).
1614 if (SERVER_IS_CHAN(server) ||
1615 !match_server(server, ctx, false)) {
1616 spin_unlock(&server->srv_lock);
1619 spin_unlock(&server->srv_lock);
1621 ++server->srv_count;
1622 spin_unlock(&cifs_tcp_ses_lock);
1623 cifs_dbg(FYI, "Existing tcp session with server found\n");
1626 spin_unlock(&cifs_tcp_ses_lock);
1631 cifs_put_tcp_session(struct TCP_Server_Info *server, int from_reconnect)
1633 struct task_struct *task;
1635 spin_lock(&cifs_tcp_ses_lock);
1636 if (--server->srv_count > 0) {
1637 spin_unlock(&cifs_tcp_ses_lock);
1641 /* srv_count can never go negative */
1642 WARN_ON(server->srv_count < 0);
1644 list_del_init(&server->tcp_ses_list);
1645 spin_unlock(&cifs_tcp_ses_lock);
1647 cancel_delayed_work_sync(&server->echo);
1651 * Avoid deadlock here: reconnect work calls
1652 * cifs_put_tcp_session() at its end. Need to be sure
1653 * that reconnect work does nothing with server pointer after
1656 cancel_delayed_work(&server->reconnect);
1658 cancel_delayed_work_sync(&server->reconnect);
1660 /* For secondary channels, we pick up ref-count on the primary server */
1661 if (SERVER_IS_CHAN(server))
1662 cifs_put_tcp_session(server->primary_server, from_reconnect);
1664 spin_lock(&server->srv_lock);
1665 server->tcpStatus = CifsExiting;
1666 spin_unlock(&server->srv_lock);
1668 cifs_crypto_secmech_release(server);
1670 kfree_sensitive(server->session_key.response);
1671 server->session_key.response = NULL;
1672 server->session_key.len = 0;
1673 kfree(server->hostname);
1674 server->hostname = NULL;
1676 task = xchg(&server->tsk, NULL);
1678 send_sig(SIGKILL, task, 1);
1681 struct TCP_Server_Info *
1682 cifs_get_tcp_session(struct smb3_fs_context *ctx,
1683 struct TCP_Server_Info *primary_server)
1685 struct TCP_Server_Info *tcp_ses = NULL;
1688 cifs_dbg(FYI, "UNC: %s\n", ctx->UNC);
1690 /* see if we already have a matching tcp_ses */
1691 tcp_ses = cifs_find_tcp_session(ctx);
1695 tcp_ses = kzalloc(sizeof(struct TCP_Server_Info), GFP_KERNEL);
1701 tcp_ses->hostname = kstrdup(ctx->server_hostname, GFP_KERNEL);
1702 if (!tcp_ses->hostname) {
1707 if (ctx->leaf_fullpath) {
1708 tcp_ses->leaf_fullpath = kstrdup(ctx->leaf_fullpath, GFP_KERNEL);
1709 if (!tcp_ses->leaf_fullpath) {
1715 if (ctx->nosharesock)
1716 tcp_ses->nosharesock = true;
1717 tcp_ses->dfs_conn = ctx->dfs_conn;
1719 tcp_ses->ops = ctx->ops;
1720 tcp_ses->vals = ctx->vals;
1722 /* Grab netns reference for this server. */
1723 cifs_set_net_ns(tcp_ses, get_net(current->nsproxy->net_ns));
1725 tcp_ses->conn_id = atomic_inc_return(&tcpSesNextId);
1726 tcp_ses->noblockcnt = ctx->rootfs;
1727 tcp_ses->noblocksnd = ctx->noblocksnd || ctx->rootfs;
1728 tcp_ses->noautotune = ctx->noautotune;
1729 tcp_ses->tcp_nodelay = ctx->sockopt_tcp_nodelay;
1730 tcp_ses->rdma = ctx->rdma;
1731 tcp_ses->in_flight = 0;
1732 tcp_ses->max_in_flight = 0;
1733 tcp_ses->credits = 1;
1734 if (primary_server) {
1735 spin_lock(&cifs_tcp_ses_lock);
1736 ++primary_server->srv_count;
1737 spin_unlock(&cifs_tcp_ses_lock);
1738 tcp_ses->primary_server = primary_server;
1740 init_waitqueue_head(&tcp_ses->response_q);
1741 init_waitqueue_head(&tcp_ses->request_q);
1742 INIT_LIST_HEAD(&tcp_ses->pending_mid_q);
1743 mutex_init(&tcp_ses->_srv_mutex);
1744 memcpy(tcp_ses->workstation_RFC1001_name,
1745 ctx->source_rfc1001_name, RFC1001_NAME_LEN_WITH_NULL);
1746 memcpy(tcp_ses->server_RFC1001_name,
1747 ctx->target_rfc1001_name, RFC1001_NAME_LEN_WITH_NULL);
1748 tcp_ses->session_estab = false;
1749 tcp_ses->sequence_number = 0;
1750 tcp_ses->channel_sequence_num = 0; /* only tracked for primary channel */
1751 tcp_ses->reconnect_instance = 1;
1752 tcp_ses->lstrp = jiffies;
1753 tcp_ses->compression.requested = ctx->compress;
1754 spin_lock_init(&tcp_ses->req_lock);
1755 spin_lock_init(&tcp_ses->srv_lock);
1756 spin_lock_init(&tcp_ses->mid_lock);
1757 INIT_LIST_HEAD(&tcp_ses->tcp_ses_list);
1758 INIT_LIST_HEAD(&tcp_ses->smb_ses_list);
1759 INIT_DELAYED_WORK(&tcp_ses->echo, cifs_echo_request);
1760 INIT_DELAYED_WORK(&tcp_ses->reconnect, smb2_reconnect_server);
1761 mutex_init(&tcp_ses->reconnect_mutex);
1762 #ifdef CONFIG_CIFS_DFS_UPCALL
1763 mutex_init(&tcp_ses->refpath_lock);
1765 memcpy(&tcp_ses->srcaddr, &ctx->srcaddr,
1766 sizeof(tcp_ses->srcaddr));
1767 memcpy(&tcp_ses->dstaddr, &ctx->dstaddr,
1768 sizeof(tcp_ses->dstaddr));
1769 if (ctx->use_client_guid)
1770 memcpy(tcp_ses->client_guid, ctx->client_guid,
1771 SMB2_CLIENT_GUID_SIZE);
1773 generate_random_uuid(tcp_ses->client_guid);
1775 * at this point we are the only ones with the pointer
1776 * to the struct since the kernel thread not created yet
1777 * no need to spinlock this init of tcpStatus or srv_count
1779 tcp_ses->tcpStatus = CifsNew;
1780 ++tcp_ses->srv_count;
1782 if (ctx->echo_interval >= SMB_ECHO_INTERVAL_MIN &&
1783 ctx->echo_interval <= SMB_ECHO_INTERVAL_MAX)
1784 tcp_ses->echo_interval = ctx->echo_interval * HZ;
1786 tcp_ses->echo_interval = SMB_ECHO_INTERVAL_DEFAULT * HZ;
1787 if (tcp_ses->rdma) {
1788 #ifndef CONFIG_CIFS_SMB_DIRECT
1789 cifs_dbg(VFS, "CONFIG_CIFS_SMB_DIRECT is not enabled\n");
1791 goto out_err_crypto_release;
1793 tcp_ses->smbd_conn = smbd_get_connection(
1794 tcp_ses, (struct sockaddr *)&ctx->dstaddr);
1795 if (tcp_ses->smbd_conn) {
1796 cifs_dbg(VFS, "RDMA transport established\n");
1798 goto smbd_connected;
1801 goto out_err_crypto_release;
1804 rc = ip_connect(tcp_ses);
1806 cifs_dbg(VFS, "Error connecting to socket. Aborting operation.\n");
1807 goto out_err_crypto_release;
1811 * since we're in a cifs function already, we know that
1812 * this will succeed. No need for try_module_get().
1814 __module_get(THIS_MODULE);
1815 tcp_ses->tsk = kthread_run(cifs_demultiplex_thread,
1817 if (IS_ERR(tcp_ses->tsk)) {
1818 rc = PTR_ERR(tcp_ses->tsk);
1819 cifs_dbg(VFS, "error %d create cifsd thread\n", rc);
1820 module_put(THIS_MODULE);
1821 goto out_err_crypto_release;
1823 tcp_ses->min_offload = ctx->min_offload;
1824 tcp_ses->retrans = ctx->retrans;
1826 * at this point we are the only ones with the pointer
1827 * to the struct since the kernel thread not created yet
1828 * no need to spinlock this update of tcpStatus
1830 spin_lock(&tcp_ses->srv_lock);
1831 tcp_ses->tcpStatus = CifsNeedNegotiate;
1832 spin_unlock(&tcp_ses->srv_lock);
1834 if ((ctx->max_credits < 20) || (ctx->max_credits > 60000))
1835 tcp_ses->max_credits = SMB2_MAX_CREDITS_AVAILABLE;
1837 tcp_ses->max_credits = ctx->max_credits;
1839 tcp_ses->nr_targets = 1;
1840 tcp_ses->ignore_signature = ctx->ignore_signature;
1841 /* thread spawned, put it on the list */
1842 spin_lock(&cifs_tcp_ses_lock);
1843 list_add(&tcp_ses->tcp_ses_list, &cifs_tcp_ses_list);
1844 spin_unlock(&cifs_tcp_ses_lock);
1846 /* queue echo request delayed work */
1847 queue_delayed_work(cifsiod_wq, &tcp_ses->echo, tcp_ses->echo_interval);
1851 out_err_crypto_release:
1852 cifs_crypto_secmech_release(tcp_ses);
1854 /* Release netns reference for this server. */
1855 put_net(cifs_net_ns(tcp_ses));
1859 if (SERVER_IS_CHAN(tcp_ses))
1860 cifs_put_tcp_session(tcp_ses->primary_server, false);
1861 kfree(tcp_ses->hostname);
1862 kfree(tcp_ses->leaf_fullpath);
1863 if (tcp_ses->ssocket) {
1864 sock_release(tcp_ses->ssocket);
1865 put_net(cifs_net_ns(tcp_ses));
1872 /* this function must be called with ses_lock and chan_lock held */
1873 static int match_session(struct cifs_ses *ses,
1874 struct smb3_fs_context *ctx,
1877 if (ctx->sectype != Unspecified &&
1878 ctx->sectype != ses->sectype)
1881 if (!match_super && ctx->dfs_root_ses != ses->dfs_root_ses)
1885 * If an existing session is limited to less channels than
1886 * requested, it should not be reused
1888 if (ses->chan_max < ctx->max_channels)
1891 switch (ses->sectype) {
1893 if (!uid_eq(ctx->cred_uid, ses->cred_uid))
1897 /* NULL username means anonymous session */
1898 if (ses->user_name == NULL) {
1904 /* anything else takes username/password */
1905 if (strncmp(ses->user_name,
1906 ctx->username ? ctx->username : "",
1907 CIFS_MAX_USERNAME_LEN))
1909 if ((ctx->username && strlen(ctx->username) != 0) &&
1910 ses->password != NULL) {
1912 /* New mount can only share sessions with an existing mount if:
1913 * 1. Both password and password2 match, or
1914 * 2. password2 of the old mount matches password of the new mount
1915 * and password of the old mount matches password2 of the new
1918 if (ses->password2 != NULL && ctx->password2 != NULL) {
1919 if (!((strncmp(ses->password, ctx->password ?
1920 ctx->password : "", CIFS_MAX_PASSWORD_LEN) == 0 &&
1921 strncmp(ses->password2, ctx->password2,
1922 CIFS_MAX_PASSWORD_LEN) == 0) ||
1923 (strncmp(ses->password, ctx->password2,
1924 CIFS_MAX_PASSWORD_LEN) == 0 &&
1925 strncmp(ses->password2, ctx->password ?
1926 ctx->password : "", CIFS_MAX_PASSWORD_LEN) == 0)))
1929 } else if ((ses->password2 == NULL && ctx->password2 != NULL) ||
1930 (ses->password2 != NULL && ctx->password2 == NULL)) {
1934 if (strncmp(ses->password, ctx->password ?
1935 ctx->password : "", CIFS_MAX_PASSWORD_LEN))
1941 if (strcmp(ctx->local_nls->charset, ses->local_nls->charset))
1948 * cifs_setup_ipc - helper to setup the IPC tcon for the session
1949 * @ses: smb session to issue the request on
1950 * @ctx: the superblock configuration context to use for building the
1951 * new tree connection for the IPC (interprocess communication RPC)
1953 * A new IPC connection is made and stored in the session
1954 * tcon_ipc. The IPC tcon has the same lifetime as the session.
1957 cifs_setup_ipc(struct cifs_ses *ses, struct smb3_fs_context *ctx)
1960 struct cifs_tcon *tcon;
1961 char unc[SERVER_NAME_LENGTH + sizeof("//x/IPC$")] = {0};
1963 struct TCP_Server_Info *server = ses->server;
1966 * If the mount request that resulted in the creation of the
1967 * session requires encryption, force IPC to be encrypted too.
1970 if (server->capabilities & SMB2_GLOBAL_CAP_ENCRYPTION)
1973 cifs_server_dbg(VFS,
1974 "IPC: server doesn't support encryption\n");
1979 /* no need to setup directory caching on IPC share, so pass in false */
1980 tcon = tcon_info_alloc(false, netfs_trace_tcon_ref_new_ipc);
1984 spin_lock(&server->srv_lock);
1985 scnprintf(unc, sizeof(unc), "\\\\%s\\IPC$", server->hostname);
1986 spin_unlock(&server->srv_lock);
1992 rc = server->ops->tree_connect(xid, ses, unc, tcon, ctx->local_nls);
1996 cifs_server_dbg(VFS, "failed to connect to IPC (rc=%d)\n", rc);
1997 tconInfoFree(tcon, netfs_trace_tcon_ref_free_ipc_fail);
2001 cifs_dbg(FYI, "IPC tcon rc=%d ipc tid=0x%x\n", rc, tcon->tid);
2003 spin_lock(&tcon->tc_lock);
2004 tcon->status = TID_GOOD;
2005 spin_unlock(&tcon->tc_lock);
2006 ses->tcon_ipc = tcon;
2011 static struct cifs_ses *
2012 cifs_find_smb_ses(struct TCP_Server_Info *server, struct smb3_fs_context *ctx)
2014 struct cifs_ses *ses, *ret = NULL;
2016 spin_lock(&cifs_tcp_ses_lock);
2017 list_for_each_entry(ses, &server->smb_ses_list, smb_ses_list) {
2018 spin_lock(&ses->ses_lock);
2019 if (ses->ses_status == SES_EXITING) {
2020 spin_unlock(&ses->ses_lock);
2023 spin_lock(&ses->chan_lock);
2024 if (match_session(ses, ctx, false)) {
2025 spin_unlock(&ses->chan_lock);
2026 spin_unlock(&ses->ses_lock);
2030 spin_unlock(&ses->chan_lock);
2031 spin_unlock(&ses->ses_lock);
2034 cifs_smb_ses_inc_refcount(ret);
2035 spin_unlock(&cifs_tcp_ses_lock);
2039 void __cifs_put_smb_ses(struct cifs_ses *ses)
2041 struct TCP_Server_Info *server = ses->server;
2042 struct cifs_tcon *tcon;
2048 spin_lock(&cifs_tcp_ses_lock);
2049 spin_lock(&ses->ses_lock);
2050 cifs_dbg(FYI, "%s: id=0x%llx ses_count=%d ses_status=%u ipc=%s\n",
2051 __func__, ses->Suid, ses->ses_count, ses->ses_status,
2052 ses->tcon_ipc ? ses->tcon_ipc->tree_name : "none");
2053 if (ses->ses_status == SES_EXITING || --ses->ses_count > 0) {
2054 spin_unlock(&ses->ses_lock);
2055 spin_unlock(&cifs_tcp_ses_lock);
2058 /* ses_count can never go negative */
2059 WARN_ON(ses->ses_count < 0);
2061 spin_lock(&ses->chan_lock);
2062 cifs_chan_clear_need_reconnect(ses, server);
2063 spin_unlock(&ses->chan_lock);
2065 do_logoff = ses->ses_status == SES_GOOD && server->ops->logoff;
2066 ses->ses_status = SES_EXITING;
2067 tcon = ses->tcon_ipc;
2068 ses->tcon_ipc = NULL;
2069 spin_unlock(&ses->ses_lock);
2070 spin_unlock(&cifs_tcp_ses_lock);
2073 * On session close, the IPC is closed and the server must release all
2074 * tcons of the session. No need to send a tree disconnect here.
2076 * Besides, it will make the server to not close durable and resilient
2077 * files on session close, as specified in MS-SMB2 3.3.5.6 Receiving an
2078 * SMB2 LOGOFF Request.
2080 tconInfoFree(tcon, netfs_trace_tcon_ref_free_ipc);
2083 rc = server->ops->logoff(xid, ses);
2084 cifs_server_dbg(FYI, "%s: Session Logoff: rc=%d\n",
2089 spin_lock(&cifs_tcp_ses_lock);
2090 list_del_init(&ses->smb_ses_list);
2091 spin_unlock(&cifs_tcp_ses_lock);
2093 /* close any extra channels */
2094 for (i = 1; i < ses->chan_count; i++) {
2095 if (ses->chans[i].iface) {
2096 kref_put(&ses->chans[i].iface->refcount, release_iface);
2097 ses->chans[i].iface = NULL;
2099 cifs_put_tcp_session(ses->chans[i].server, 0);
2100 ses->chans[i].server = NULL;
2103 /* we now account for primary channel in iface->refcount */
2104 if (ses->chans[0].iface) {
2105 kref_put(&ses->chans[0].iface->refcount, release_iface);
2106 ses->chans[0].server = NULL;
2110 cifs_put_tcp_session(server, 0);
2115 /* strlen("cifs:a:") + CIFS_MAX_DOMAINNAME_LEN + 1 */
2116 #define CIFSCREDS_DESC_SIZE (7 + CIFS_MAX_DOMAINNAME_LEN + 1)
2118 /* Populate username and pw fields from keyring if possible */
2120 cifs_set_cifscreds(struct smb3_fs_context *ctx, struct cifs_ses *ses)
2124 const char *delim, *payload;
2128 struct TCP_Server_Info *server = ses->server;
2129 struct sockaddr_in *sa;
2130 struct sockaddr_in6 *sa6;
2131 const struct user_key_payload *upayload;
2133 desc = kmalloc(CIFSCREDS_DESC_SIZE, GFP_KERNEL);
2137 /* try to find an address key first */
2138 switch (server->dstaddr.ss_family) {
2140 sa = (struct sockaddr_in *)&server->dstaddr;
2141 sprintf(desc, "cifs:a:%pI4", &sa->sin_addr.s_addr);
2144 sa6 = (struct sockaddr_in6 *)&server->dstaddr;
2145 sprintf(desc, "cifs:a:%pI6c", &sa6->sin6_addr.s6_addr);
2148 cifs_dbg(FYI, "Bad ss_family (%hu)\n",
2149 server->dstaddr.ss_family);
2154 cifs_dbg(FYI, "%s: desc=%s\n", __func__, desc);
2155 key = request_key(&key_type_logon, desc, "");
2157 if (!ses->domainName) {
2158 cifs_dbg(FYI, "domainName is NULL\n");
2163 /* didn't work, try to find a domain key */
2164 sprintf(desc, "cifs:d:%s", ses->domainName);
2165 cifs_dbg(FYI, "%s: desc=%s\n", __func__, desc);
2166 key = request_key(&key_type_logon, desc, "");
2174 down_read(&key->sem);
2175 upayload = user_key_payload_locked(key);
2176 if (IS_ERR_OR_NULL(upayload)) {
2177 rc = upayload ? PTR_ERR(upayload) : -EINVAL;
2181 /* find first : in payload */
2182 payload = upayload->data;
2183 delim = strnchr(payload, upayload->datalen, ':');
2184 cifs_dbg(FYI, "payload=%s\n", payload);
2186 cifs_dbg(FYI, "Unable to find ':' in payload (datalen=%d)\n",
2192 len = delim - payload;
2193 if (len > CIFS_MAX_USERNAME_LEN || len <= 0) {
2194 cifs_dbg(FYI, "Bad value from username search (len=%zd)\n",
2200 ctx->username = kstrndup(payload, len, GFP_KERNEL);
2201 if (!ctx->username) {
2202 cifs_dbg(FYI, "Unable to allocate %zd bytes for username\n",
2207 cifs_dbg(FYI, "%s: username=%s\n", __func__, ctx->username);
2209 len = key->datalen - (len + 1);
2210 if (len > CIFS_MAX_PASSWORD_LEN || len <= 0) {
2211 cifs_dbg(FYI, "Bad len for password search (len=%zd)\n", len);
2213 kfree(ctx->username);
2214 ctx->username = NULL;
2219 /* BB consider adding support for password2 (Key Rotation) for multiuser in future */
2220 ctx->password = kstrndup(delim, len, GFP_KERNEL);
2221 if (!ctx->password) {
2222 cifs_dbg(FYI, "Unable to allocate %zd bytes for password\n",
2225 kfree(ctx->username);
2226 ctx->username = NULL;
2231 * If we have a domain key then we must set the domainName in the
2234 if (is_domain && ses->domainName) {
2235 ctx->domainname = kstrdup(ses->domainName, GFP_KERNEL);
2236 if (!ctx->domainname) {
2237 cifs_dbg(FYI, "Unable to allocate %zd bytes for domain\n",
2240 kfree(ctx->username);
2241 ctx->username = NULL;
2242 kfree_sensitive(ctx->password);
2243 /* no need to free ctx->password2 since not allocated in this path */
2244 ctx->password = NULL;
2249 strscpy(ctx->workstation_name, ses->workstation_name, sizeof(ctx->workstation_name));
2256 cifs_dbg(FYI, "%s: returning %d\n", __func__, rc);
2259 #else /* ! CONFIG_KEYS */
2261 cifs_set_cifscreds(struct smb3_fs_context *ctx __attribute__((unused)),
2262 struct cifs_ses *ses __attribute__((unused)))
2266 #endif /* CONFIG_KEYS */
2269 * cifs_get_smb_ses - get a session matching @ctx data from @server
2270 * @server: server to setup the session to
2271 * @ctx: superblock configuration context to use to setup the session
2273 * This function assumes it is being called from cifs_mount() where we
2274 * already got a server reference (server refcount +1). See
2275 * cifs_get_tcon() for refcount explanations.
2278 cifs_get_smb_ses(struct TCP_Server_Info *server, struct smb3_fs_context *ctx)
2283 struct cifs_ses *ses;
2284 struct sockaddr_in *addr = (struct sockaddr_in *)&server->dstaddr;
2285 struct sockaddr_in6 *addr6 = (struct sockaddr_in6 *)&server->dstaddr;
2289 ses = cifs_find_smb_ses(server, ctx);
2291 cifs_dbg(FYI, "Existing smb sess found (status=%d)\n",
2294 spin_lock(&ses->chan_lock);
2295 if (cifs_chan_needs_reconnect(ses, server)) {
2296 spin_unlock(&ses->chan_lock);
2297 cifs_dbg(FYI, "Session needs reconnect\n");
2299 mutex_lock(&ses->session_mutex);
2302 rc = cifs_negotiate_protocol(xid, ses, server);
2304 mutex_unlock(&ses->session_mutex);
2305 /* problem -- put our ses reference */
2306 cifs_put_smb_ses(ses);
2311 rc = cifs_setup_session(xid, ses, server,
2314 if (((rc == -EACCES) || (rc == -EKEYEXPIRED) ||
2315 (rc == -EKEYREVOKED)) && !retries && ses->password2) {
2317 cifs_dbg(FYI, "Session reconnect failed, retrying with alternate password\n");
2318 swap(ses->password, ses->password2);
2319 goto retry_old_session;
2321 mutex_unlock(&ses->session_mutex);
2322 /* problem -- put our reference */
2323 cifs_put_smb_ses(ses);
2327 mutex_unlock(&ses->session_mutex);
2329 spin_lock(&ses->chan_lock);
2331 spin_unlock(&ses->chan_lock);
2333 /* existing SMB ses has a server reference already */
2334 cifs_put_tcp_session(server, 0);
2341 cifs_dbg(FYI, "Existing smb sess not found\n");
2342 ses = sesInfoAlloc();
2346 /* new SMB session uses our server ref */
2347 ses->server = server;
2348 if (server->dstaddr.ss_family == AF_INET6)
2349 sprintf(ses->ip_addr, "%pI6", &addr6->sin6_addr);
2351 sprintf(ses->ip_addr, "%pI4", &addr->sin_addr);
2353 if (ctx->username) {
2354 ses->user_name = kstrdup(ctx->username, GFP_KERNEL);
2355 if (!ses->user_name)
2359 /* ctx->password freed at unmount */
2360 if (ctx->password) {
2361 ses->password = kstrdup(ctx->password, GFP_KERNEL);
2365 /* ctx->password freed at unmount */
2366 if (ctx->password2) {
2367 ses->password2 = kstrdup(ctx->password2, GFP_KERNEL);
2368 if (!ses->password2)
2371 if (ctx->domainname) {
2372 ses->domainName = kstrdup(ctx->domainname, GFP_KERNEL);
2373 if (!ses->domainName)
2377 strscpy(ses->workstation_name, ctx->workstation_name, sizeof(ses->workstation_name));
2379 if (ctx->domainauto)
2380 ses->domainAuto = ctx->domainauto;
2381 ses->cred_uid = ctx->cred_uid;
2382 ses->linux_uid = ctx->linux_uid;
2384 ses->sectype = ctx->sectype;
2385 ses->sign = ctx->sign;
2388 *Explicitly marking upcall_target mount option for easier handling
2389 * by cifs_spnego.c and eventually cifs.upcall.c
2392 switch (ctx->upcall_target) {
2393 case UPTARGET_UNSPECIFIED: /* default to app */
2395 ses->upcall_target = UPTARGET_APP;
2397 case UPTARGET_MOUNT:
2398 ses->upcall_target = UPTARGET_MOUNT;
2401 // should never happen
2402 ses->upcall_target = UPTARGET_APP;
2406 ses->local_nls = load_nls(ctx->local_nls->charset);
2408 /* add server as first channel */
2409 spin_lock(&ses->chan_lock);
2410 ses->chans[0].server = server;
2411 ses->chan_count = 1;
2412 ses->chan_max = ctx->multichannel ? ctx->max_channels:1;
2413 ses->chans_need_reconnect = 1;
2414 spin_unlock(&ses->chan_lock);
2417 mutex_lock(&ses->session_mutex);
2418 rc = cifs_negotiate_protocol(xid, ses, server);
2420 rc = cifs_setup_session(xid, ses, server, ctx->local_nls);
2421 mutex_unlock(&ses->session_mutex);
2423 /* each channel uses a different signing key */
2424 spin_lock(&ses->chan_lock);
2425 memcpy(ses->chans[0].signkey, ses->smb3signingkey,
2426 sizeof(ses->smb3signingkey));
2427 spin_unlock(&ses->chan_lock);
2430 if (((rc == -EACCES) || (rc == -EKEYEXPIRED) ||
2431 (rc == -EKEYREVOKED)) && !retries && ses->password2) {
2433 cifs_dbg(FYI, "Session setup failed, retrying with alternate password\n");
2434 swap(ses->password, ses->password2);
2435 goto retry_new_session;
2441 * success, put it on the list and add it as first channel
2442 * note: the session becomes active soon after this. So you'll
2443 * need to lock before changing something in the session.
2445 spin_lock(&cifs_tcp_ses_lock);
2446 ses->dfs_root_ses = ctx->dfs_root_ses;
2447 list_add(&ses->smb_ses_list, &server->smb_ses_list);
2448 spin_unlock(&cifs_tcp_ses_lock);
2450 cifs_setup_ipc(ses, ctx);
2462 /* this function must be called with tc_lock held */
2463 static int match_tcon(struct cifs_tcon *tcon, struct smb3_fs_context *ctx)
2465 struct TCP_Server_Info *server = tcon->ses->server;
2467 if (tcon->status == TID_EXITING)
2470 if (tcon->origin_fullpath) {
2472 !dfs_src_pathname_equal(ctx->source,
2473 tcon->origin_fullpath))
2475 } else if (!server->leaf_fullpath &&
2476 strncmp(tcon->tree_name, ctx->UNC, MAX_TREE_SIZE)) {
2479 if (tcon->seal != ctx->seal)
2481 if (tcon->snapshot_time != ctx->snapshot_time)
2483 if (tcon->handle_timeout != ctx->handle_timeout)
2485 if (tcon->no_lease != ctx->no_lease)
2487 if (tcon->nodelete != ctx->nodelete)
2492 static struct cifs_tcon *
2493 cifs_find_tcon(struct cifs_ses *ses, struct smb3_fs_context *ctx)
2495 struct cifs_tcon *tcon;
2497 spin_lock(&cifs_tcp_ses_lock);
2498 list_for_each_entry(tcon, &ses->tcon_list, tcon_list) {
2499 spin_lock(&tcon->tc_lock);
2500 if (!match_tcon(tcon, ctx)) {
2501 spin_unlock(&tcon->tc_lock);
2505 trace_smb3_tcon_ref(tcon->debug_id, tcon->tc_count,
2506 netfs_trace_tcon_ref_get_find);
2507 spin_unlock(&tcon->tc_lock);
2508 spin_unlock(&cifs_tcp_ses_lock);
2511 spin_unlock(&cifs_tcp_ses_lock);
2516 cifs_put_tcon(struct cifs_tcon *tcon, enum smb3_tcon_ref_trace trace)
2519 struct cifs_ses *ses;
2520 LIST_HEAD(ses_list);
2523 * IPC tcon share the lifetime of their session and are
2524 * destroyed in the session put function
2526 if (tcon == NULL || tcon->ipc)
2530 cifs_dbg(FYI, "%s: tc_count=%d\n", __func__, tcon->tc_count);
2531 spin_lock(&cifs_tcp_ses_lock);
2532 spin_lock(&tcon->tc_lock);
2533 trace_smb3_tcon_ref(tcon->debug_id, tcon->tc_count - 1, trace);
2534 if (--tcon->tc_count > 0) {
2535 spin_unlock(&tcon->tc_lock);
2536 spin_unlock(&cifs_tcp_ses_lock);
2540 /* tc_count can never go negative */
2541 WARN_ON(tcon->tc_count < 0);
2543 list_del_init(&tcon->tcon_list);
2544 tcon->status = TID_EXITING;
2545 spin_unlock(&tcon->tc_lock);
2546 spin_unlock(&cifs_tcp_ses_lock);
2548 /* cancel polling of interfaces */
2549 cancel_delayed_work_sync(&tcon->query_interfaces);
2550 #ifdef CONFIG_CIFS_DFS_UPCALL
2551 cancel_delayed_work_sync(&tcon->dfs_cache_work);
2552 list_replace_init(&tcon->dfs_ses_list, &ses_list);
2555 if (tcon->use_witness) {
2558 rc = cifs_swn_unregister(tcon);
2560 cifs_dbg(VFS, "%s: Failed to unregister for witness notifications: %d\n",
2566 if (ses->server->ops->tree_disconnect)
2567 ses->server->ops->tree_disconnect(xid, tcon);
2570 cifs_fscache_release_super_cookie(tcon);
2571 tconInfoFree(tcon, netfs_trace_tcon_ref_free);
2572 cifs_put_smb_ses(ses);
2573 #ifdef CONFIG_CIFS_DFS_UPCALL
2574 dfs_put_root_smb_sessions(&ses_list);
2579 * cifs_get_tcon - get a tcon matching @ctx data from @ses
2580 * @ses: smb session to issue the request on
2581 * @ctx: the superblock configuration context to use for building the
2583 * - tcon refcount is the number of mount points using the tcon.
2584 * - ses refcount is the number of tcon using the session.
2586 * 1. This function assumes it is being called from cifs_mount() where
2587 * we already got a session reference (ses refcount +1).
2589 * 2. Since we're in the context of adding a mount point, the end
2590 * result should be either:
2592 * a) a new tcon already allocated with refcount=1 (1 mount point) and
2593 * its session refcount incremented (1 new tcon). This +1 was
2594 * already done in (1).
2596 * b) an existing tcon with refcount+1 (add a mount point to it) and
2597 * identical ses refcount (no new tcon). Because of (1) we need to
2598 * decrement the ses refcount.
2600 static struct cifs_tcon *
2601 cifs_get_tcon(struct cifs_ses *ses, struct smb3_fs_context *ctx)
2603 struct cifs_tcon *tcon;
2607 tcon = cifs_find_tcon(ses, ctx);
2610 * tcon has refcount already incremented but we need to
2611 * decrement extra ses reference gotten by caller (case b)
2613 cifs_dbg(FYI, "Found match on UNC path\n");
2614 cifs_put_smb_ses(ses);
2618 if (!ses->server->ops->tree_connect) {
2623 if (ses->server->dialect >= SMB20_PROT_ID &&
2624 (ses->server->capabilities & SMB2_GLOBAL_CAP_DIRECTORY_LEASING))
2625 nohandlecache = ctx->nohandlecache || !dir_cache_timeout;
2627 nohandlecache = true;
2628 tcon = tcon_info_alloc(!nohandlecache, netfs_trace_tcon_ref_new);
2633 tcon->nohandlecache = nohandlecache;
2635 if (ctx->snapshot_time) {
2636 if (ses->server->vals->protocol_id == 0) {
2638 "Use SMB2 or later for snapshot mount option\n");
2642 tcon->snapshot_time = ctx->snapshot_time;
2645 if (ctx->handle_timeout) {
2646 if (ses->server->vals->protocol_id == 0) {
2648 "Use SMB2.1 or later for handle timeout option\n");
2652 tcon->handle_timeout = ctx->handle_timeout;
2656 if (ctx->password) {
2657 tcon->password = kstrdup(ctx->password, GFP_KERNEL);
2658 if (!tcon->password) {
2665 if (ses->server->vals->protocol_id == 0) {
2667 "SMB3 or later required for encryption\n");
2670 } else if (tcon->ses->server->capabilities &
2671 SMB2_GLOBAL_CAP_ENCRYPTION)
2674 cifs_dbg(VFS, "Encryption is not supported on share\n");
2680 if (ctx->linux_ext) {
2681 if (ses->server->posix_ext_supported) {
2682 tcon->posix_extensions = true;
2683 pr_warn_once("SMB3.11 POSIX Extensions are experimental\n");
2684 } else if ((ses->server->vals->protocol_id == SMB311_PROT_ID) ||
2685 (strcmp(ses->server->vals->version_string,
2686 SMB3ANY_VERSION_STRING) == 0) ||
2687 (strcmp(ses->server->vals->version_string,
2688 SMBDEFAULT_VERSION_STRING) == 0)) {
2689 cifs_dbg(VFS, "Server does not support mounting with posix SMB3.11 extensions\n");
2692 } else if (ses->server->vals->protocol_id == SMB10_PROT_ID)
2694 cifs_dbg(FYI, "Unix Extensions requested on SMB1 mount\n");
2696 cifs_dbg(VFS, "SMB1 Unix Extensions not supported by server\n");
2701 "Check vers= mount option. SMB3.11 disabled but required for POSIX extensions\n");
2708 rc = ses->server->ops->tree_connect(xid, ses, ctx->UNC, tcon,
2711 cifs_dbg(FYI, "Tcon rc = %d\n", rc);
2715 tcon->use_persistent = false;
2716 /* check if SMB2 or later, CIFS does not support persistent handles */
2717 if (ctx->persistent) {
2718 if (ses->server->vals->protocol_id == 0) {
2720 "SMB3 or later required for persistent handles\n");
2723 } else if (ses->server->capabilities &
2724 SMB2_GLOBAL_CAP_PERSISTENT_HANDLES)
2725 tcon->use_persistent = true;
2726 else /* persistent handles requested but not supported */ {
2728 "Persistent handles not supported on share\n");
2732 } else if ((tcon->capabilities & SMB2_SHARE_CAP_CONTINUOUS_AVAILABILITY)
2733 && (ses->server->capabilities & SMB2_GLOBAL_CAP_PERSISTENT_HANDLES)
2734 && (ctx->nopersistent == false)) {
2735 cifs_dbg(FYI, "enabling persistent handles\n");
2736 tcon->use_persistent = true;
2737 } else if (ctx->resilient) {
2738 if (ses->server->vals->protocol_id == 0) {
2740 "SMB2.1 or later required for resilient handles\n");
2744 tcon->use_resilient = true;
2747 tcon->use_witness = false;
2748 if (IS_ENABLED(CONFIG_CIFS_SWN_UPCALL) && ctx->witness) {
2749 if (ses->server->vals->protocol_id >= SMB30_PROT_ID) {
2750 if (tcon->capabilities & SMB2_SHARE_CAP_CLUSTER) {
2752 * Set witness in use flag in first place
2753 * to retry registration in the echo task
2755 tcon->use_witness = true;
2756 /* And try to register immediately */
2757 rc = cifs_swn_register(tcon);
2759 cifs_dbg(VFS, "Failed to register for witness notifications: %d\n", rc);
2763 /* TODO: try to extend for non-cluster uses (eg multichannel) */
2764 cifs_dbg(VFS, "witness requested on mount but no CLUSTER capability on share\n");
2769 cifs_dbg(VFS, "SMB3 or later required for witness option\n");
2775 /* If the user really knows what they are doing they can override */
2776 if (tcon->share_flags & SMB2_SHAREFLAG_NO_CACHING) {
2778 cifs_dbg(VFS, "cache=ro requested on mount but NO_CACHING flag set on share\n");
2779 else if (ctx->cache_rw)
2780 cifs_dbg(VFS, "cache=singleclient requested on mount but NO_CACHING flag set on share\n");
2783 if (ctx->no_lease) {
2784 if (ses->server->vals->protocol_id == 0) {
2786 "SMB2 or later required for nolease option\n");
2790 tcon->no_lease = ctx->no_lease;
2794 * We can have only one retry value for a connection to a share so for
2795 * resources mounted more than once to the same server share the last
2796 * value passed in for the retry flag is used.
2798 tcon->retry = ctx->retry;
2799 tcon->nocase = ctx->nocase;
2800 tcon->broken_sparse_sup = ctx->no_sparse;
2801 tcon->max_cached_dirs = ctx->max_cached_dirs;
2802 tcon->nodelete = ctx->nodelete;
2803 tcon->local_lease = ctx->local_lease;
2804 INIT_LIST_HEAD(&tcon->pending_opens);
2805 tcon->status = TID_GOOD;
2807 INIT_DELAYED_WORK(&tcon->query_interfaces,
2808 smb2_query_server_interfaces);
2809 if (ses->server->dialect >= SMB30_PROT_ID &&
2810 (ses->server->capabilities & SMB2_GLOBAL_CAP_MULTI_CHANNEL)) {
2811 /* schedule query interfaces poll */
2812 queue_delayed_work(cifsiod_wq, &tcon->query_interfaces,
2813 (SMB_INTERFACE_POLL_INTERVAL * HZ));
2815 #ifdef CONFIG_CIFS_DFS_UPCALL
2816 INIT_DELAYED_WORK(&tcon->dfs_cache_work, dfs_cache_refresh);
2818 spin_lock(&cifs_tcp_ses_lock);
2819 list_add(&tcon->tcon_list, &ses->tcon_list);
2820 spin_unlock(&cifs_tcp_ses_lock);
2825 tconInfoFree(tcon, netfs_trace_tcon_ref_free_fail);
2830 cifs_put_tlink(struct tcon_link *tlink)
2832 if (!tlink || IS_ERR(tlink))
2835 if (!atomic_dec_and_test(&tlink->tl_count) ||
2836 test_bit(TCON_LINK_IN_TREE, &tlink->tl_flags)) {
2837 tlink->tl_time = jiffies;
2841 if (!IS_ERR(tlink_tcon(tlink)))
2842 cifs_put_tcon(tlink_tcon(tlink), netfs_trace_tcon_ref_put_tlink);
2847 compare_mount_options(struct super_block *sb, struct cifs_mnt_data *mnt_data)
2849 struct cifs_sb_info *old = CIFS_SB(sb);
2850 struct cifs_sb_info *new = mnt_data->cifs_sb;
2851 unsigned int oldflags = old->mnt_cifs_flags & CIFS_MOUNT_MASK;
2852 unsigned int newflags = new->mnt_cifs_flags & CIFS_MOUNT_MASK;
2854 if ((sb->s_flags & CIFS_MS_MASK) != (mnt_data->flags & CIFS_MS_MASK))
2857 if (old->mnt_cifs_serverino_autodisabled)
2858 newflags &= ~CIFS_MOUNT_SERVER_INUM;
2860 if (oldflags != newflags)
2864 * We want to share sb only if we don't specify an r/wsize or
2865 * specified r/wsize is greater than or equal to existing one.
2867 if (new->ctx->wsize && new->ctx->wsize < old->ctx->wsize)
2870 if (new->ctx->rsize && new->ctx->rsize < old->ctx->rsize)
2873 if (!uid_eq(old->ctx->linux_uid, new->ctx->linux_uid) ||
2874 !gid_eq(old->ctx->linux_gid, new->ctx->linux_gid))
2877 if (old->ctx->file_mode != new->ctx->file_mode ||
2878 old->ctx->dir_mode != new->ctx->dir_mode)
2881 if (strcmp(old->local_nls->charset, new->local_nls->charset))
2884 if (old->ctx->acregmax != new->ctx->acregmax)
2886 if (old->ctx->acdirmax != new->ctx->acdirmax)
2888 if (old->ctx->closetimeo != new->ctx->closetimeo)
2890 if (old->ctx->reparse_type != new->ctx->reparse_type)
2896 static int match_prepath(struct super_block *sb,
2897 struct cifs_tcon *tcon,
2898 struct cifs_mnt_data *mnt_data)
2900 struct smb3_fs_context *ctx = mnt_data->ctx;
2901 struct cifs_sb_info *old = CIFS_SB(sb);
2902 struct cifs_sb_info *new = mnt_data->cifs_sb;
2903 bool old_set = (old->mnt_cifs_flags & CIFS_MOUNT_USE_PREFIX_PATH) &&
2905 bool new_set = (new->mnt_cifs_flags & CIFS_MOUNT_USE_PREFIX_PATH) &&
2908 if (tcon->origin_fullpath &&
2909 dfs_src_pathname_equal(tcon->origin_fullpath, ctx->source))
2912 if (old_set && new_set && !strcmp(new->prepath, old->prepath))
2914 else if (!old_set && !new_set)
2921 cifs_match_super(struct super_block *sb, void *data)
2923 struct cifs_mnt_data *mnt_data = data;
2924 struct smb3_fs_context *ctx;
2925 struct cifs_sb_info *cifs_sb;
2926 struct TCP_Server_Info *tcp_srv;
2927 struct cifs_ses *ses;
2928 struct cifs_tcon *tcon;
2929 struct tcon_link *tlink;
2932 spin_lock(&cifs_tcp_ses_lock);
2933 cifs_sb = CIFS_SB(sb);
2935 /* We do not want to use a superblock that has been shutdown */
2936 if (CIFS_MOUNT_SHUTDOWN & cifs_sb->mnt_cifs_flags) {
2937 spin_unlock(&cifs_tcp_ses_lock);
2941 tlink = cifs_get_tlink(cifs_sb_master_tlink(cifs_sb));
2942 if (IS_ERR_OR_NULL(tlink)) {
2943 pr_warn_once("%s: skip super matching due to bad tlink(%p)\n",
2945 spin_unlock(&cifs_tcp_ses_lock);
2948 tcon = tlink_tcon(tlink);
2950 tcp_srv = ses->server;
2952 ctx = mnt_data->ctx;
2954 spin_lock(&tcp_srv->srv_lock);
2955 spin_lock(&ses->ses_lock);
2956 spin_lock(&ses->chan_lock);
2957 spin_lock(&tcon->tc_lock);
2958 if (!match_server(tcp_srv, ctx, true) ||
2959 !match_session(ses, ctx, true) ||
2960 !match_tcon(tcon, ctx) ||
2961 !match_prepath(sb, tcon, mnt_data)) {
2966 rc = compare_mount_options(sb, mnt_data);
2968 spin_unlock(&tcon->tc_lock);
2969 spin_unlock(&ses->chan_lock);
2970 spin_unlock(&ses->ses_lock);
2971 spin_unlock(&tcp_srv->srv_lock);
2973 spin_unlock(&cifs_tcp_ses_lock);
2974 cifs_put_tlink(tlink);
2978 #ifdef CONFIG_DEBUG_LOCK_ALLOC
2979 static struct lock_class_key cifs_key[2];
2980 static struct lock_class_key cifs_slock_key[2];
2983 cifs_reclassify_socket4(struct socket *sock)
2985 struct sock *sk = sock->sk;
2987 BUG_ON(!sock_allow_reclassification(sk));
2988 sock_lock_init_class_and_name(sk, "slock-AF_INET-CIFS",
2989 &cifs_slock_key[0], "sk_lock-AF_INET-CIFS", &cifs_key[0]);
2993 cifs_reclassify_socket6(struct socket *sock)
2995 struct sock *sk = sock->sk;
2997 BUG_ON(!sock_allow_reclassification(sk));
2998 sock_lock_init_class_and_name(sk, "slock-AF_INET6-CIFS",
2999 &cifs_slock_key[1], "sk_lock-AF_INET6-CIFS", &cifs_key[1]);
3003 cifs_reclassify_socket4(struct socket *sock)
3008 cifs_reclassify_socket6(struct socket *sock)
3013 /* See RFC1001 section 14 on representation of Netbios names */
3014 static void rfc1002mangle(char *target, char *source, unsigned int length)
3018 for (i = 0, j = 0; i < (length); i++) {
3019 /* mask a nibble at a time and encode */
3020 target[j] = 'A' + (0x0F & (source[i] >> 4));
3021 target[j+1] = 'A' + (0x0F & source[i]);
3028 bind_socket(struct TCP_Server_Info *server)
3032 if (server->srcaddr.ss_family != AF_UNSPEC) {
3033 /* Bind to the specified local IP address */
3034 struct socket *socket = server->ssocket;
3036 rc = kernel_bind(socket,
3037 (struct sockaddr *) &server->srcaddr,
3038 sizeof(server->srcaddr));
3040 struct sockaddr_in *saddr4;
3041 struct sockaddr_in6 *saddr6;
3043 saddr4 = (struct sockaddr_in *)&server->srcaddr;
3044 saddr6 = (struct sockaddr_in6 *)&server->srcaddr;
3045 if (saddr6->sin6_family == AF_INET6)
3046 cifs_server_dbg(VFS, "Failed to bind to: %pI6c, error: %d\n",
3047 &saddr6->sin6_addr, rc);
3049 cifs_server_dbg(VFS, "Failed to bind to: %pI4, error: %d\n",
3050 &saddr4->sin_addr.s_addr, rc);
3057 ip_rfc1001_connect(struct TCP_Server_Info *server)
3061 * some servers require RFC1001 sessinit before sending
3062 * negprot - BB check reconnection in case where second
3063 * sessinit is sent but no second negprot
3065 struct rfc1002_session_packet req = {};
3066 struct smb_hdr *smb_buf = (struct smb_hdr *)&req;
3069 req.trailer.session_req.called_len = sizeof(req.trailer.session_req.called_name);
3071 if (server->server_RFC1001_name[0] != 0)
3072 rfc1002mangle(req.trailer.session_req.called_name,
3073 server->server_RFC1001_name,
3074 RFC1001_NAME_LEN_WITH_NULL);
3076 rfc1002mangle(req.trailer.session_req.called_name,
3077 DEFAULT_CIFS_CALLED_NAME,
3078 RFC1001_NAME_LEN_WITH_NULL);
3080 req.trailer.session_req.calling_len = sizeof(req.trailer.session_req.calling_name);
3082 /* calling name ends in null (byte 16) from old smb convention */
3083 if (server->workstation_RFC1001_name[0] != 0)
3084 rfc1002mangle(req.trailer.session_req.calling_name,
3085 server->workstation_RFC1001_name,
3086 RFC1001_NAME_LEN_WITH_NULL);
3088 rfc1002mangle(req.trailer.session_req.calling_name,
3090 RFC1001_NAME_LEN_WITH_NULL);
3093 * As per rfc1002, @len must be the number of bytes that follows the
3094 * length field of a rfc1002 session request payload.
3096 len = sizeof(req) - offsetof(struct rfc1002_session_packet, trailer.session_req);
3098 smb_buf->smb_buf_length = cpu_to_be32((RFC1002_SESSION_REQUEST << 24) | len);
3099 rc = smb_send(server, smb_buf, len);
3101 * RFC1001 layer in at least one server requires very short break before
3102 * negprot presumably because not expecting negprot to follow so fast.
3103 * This is a simple solution that works without complicating the code
3104 * and causes no significant slowing down on mount for everyone else
3106 usleep_range(1000, 2000);
3112 generic_ip_connect(struct TCP_Server_Info *server)
3114 struct sockaddr *saddr;
3115 struct socket *socket;
3120 saddr = (struct sockaddr *) &server->dstaddr;
3122 if (server->dstaddr.ss_family == AF_INET6) {
3123 struct sockaddr_in6 *ipv6 = (struct sockaddr_in6 *)&server->dstaddr;
3125 sport = ipv6->sin6_port;
3126 slen = sizeof(struct sockaddr_in6);
3128 cifs_dbg(FYI, "%s: connecting to [%pI6]:%d\n", __func__, &ipv6->sin6_addr,
3131 struct sockaddr_in *ipv4 = (struct sockaddr_in *)&server->dstaddr;
3133 sport = ipv4->sin_port;
3134 slen = sizeof(struct sockaddr_in);
3136 cifs_dbg(FYI, "%s: connecting to %pI4:%d\n", __func__, &ipv4->sin_addr,
3140 if (server->ssocket) {
3141 socket = server->ssocket;
3143 struct net *net = cifs_net_ns(server);
3145 rc = sock_create_kern(net, sfamily, SOCK_STREAM, IPPROTO_TCP, &server->ssocket);
3147 cifs_server_dbg(VFS, "Error %d creating socket\n", rc);
3152 * Grab netns reference for the socket.
3154 * It'll be released here, on error, or in clean_demultiplex_info() upon server
3159 /* BB other socket options to set KEEPALIVE, NODELAY? */
3160 cifs_dbg(FYI, "Socket created\n");
3161 socket = server->ssocket;
3162 socket->sk->sk_allocation = GFP_NOFS;
3163 socket->sk->sk_use_task_frag = false;
3164 if (sfamily == AF_INET6)
3165 cifs_reclassify_socket6(socket);
3167 cifs_reclassify_socket4(socket);
3170 rc = bind_socket(server);
3172 put_net(cifs_net_ns(server));
3177 * Eventually check for other socket options to change from
3178 * the default. sock_setsockopt not used because it expects
3181 socket->sk->sk_rcvtimeo = 7 * HZ;
3182 socket->sk->sk_sndtimeo = 5 * HZ;
3184 /* make the bufsizes depend on wsize/rsize and max requests */
3185 if (server->noautotune) {
3186 if (socket->sk->sk_sndbuf < (200 * 1024))
3187 socket->sk->sk_sndbuf = 200 * 1024;
3188 if (socket->sk->sk_rcvbuf < (140 * 1024))
3189 socket->sk->sk_rcvbuf = 140 * 1024;
3192 if (server->tcp_nodelay)
3193 tcp_sock_set_nodelay(socket->sk);
3195 cifs_dbg(FYI, "sndbuf %d rcvbuf %d rcvtimeo 0x%lx\n",
3196 socket->sk->sk_sndbuf,
3197 socket->sk->sk_rcvbuf, socket->sk->sk_rcvtimeo);
3199 rc = kernel_connect(socket, saddr, slen,
3200 server->noblockcnt ? O_NONBLOCK : 0);
3202 * When mounting SMB root file systems, we do not want to block in
3203 * connect. Otherwise bail out and then let cifs_reconnect() perform
3204 * reconnect failover - if possible.
3206 if (server->noblockcnt && rc == -EINPROGRESS)
3209 cifs_dbg(FYI, "Error %d connecting to server\n", rc);
3210 trace_smb3_connect_err(server->hostname, server->conn_id, &server->dstaddr, rc);
3211 put_net(cifs_net_ns(server));
3212 sock_release(socket);
3213 server->ssocket = NULL;
3216 trace_smb3_connect_done(server->hostname, server->conn_id, &server->dstaddr);
3217 if (sport == htons(RFC1001_PORT))
3218 rc = ip_rfc1001_connect(server);
3221 put_net(cifs_net_ns(server));
3227 ip_connect(struct TCP_Server_Info *server)
3230 struct sockaddr_in6 *addr6 = (struct sockaddr_in6 *)&server->dstaddr;
3231 struct sockaddr_in *addr = (struct sockaddr_in *)&server->dstaddr;
3233 if (server->dstaddr.ss_family == AF_INET6)
3234 sport = &addr6->sin6_port;
3236 sport = &addr->sin_port;
3241 /* try with 445 port at first */
3242 *sport = htons(CIFS_PORT);
3244 rc = generic_ip_connect(server);
3248 /* if it failed, try with 139 port */
3249 *sport = htons(RFC1001_PORT);
3252 return generic_ip_connect(server);
3255 #ifdef CONFIG_CIFS_ALLOW_INSECURE_LEGACY
3256 void reset_cifs_unix_caps(unsigned int xid, struct cifs_tcon *tcon,
3257 struct cifs_sb_info *cifs_sb, struct smb3_fs_context *ctx)
3260 * If we are reconnecting then should we check to see if
3261 * any requested capabilities changed locally e.g. via
3262 * remount but we can not do much about it here
3263 * if they have (even if we could detect it by the following)
3264 * Perhaps we could add a backpointer to array of sb from tcon
3265 * or if we change to make all sb to same share the same
3266 * sb as NFS - then we only have one backpointer to sb.
3267 * What if we wanted to mount the server share twice once with
3268 * and once without posixacls or posix paths?
3270 __u64 saved_cap = le64_to_cpu(tcon->fsUnixInfo.Capability);
3272 if (ctx && ctx->no_linux_ext) {
3273 tcon->fsUnixInfo.Capability = 0;
3274 tcon->unix_ext = 0; /* Unix Extensions disabled */
3275 cifs_dbg(FYI, "Linux protocol extensions disabled\n");
3278 tcon->unix_ext = 1; /* Unix Extensions supported */
3280 if (!tcon->unix_ext) {
3281 cifs_dbg(FYI, "Unix extensions disabled so not set on reconnect\n");
3285 if (!CIFSSMBQFSUnixInfo(xid, tcon)) {
3286 __u64 cap = le64_to_cpu(tcon->fsUnixInfo.Capability);
3288 cifs_dbg(FYI, "unix caps which server supports %lld\n", cap);
3290 * check for reconnect case in which we do not
3291 * want to change the mount behavior if we can avoid it
3295 * turn off POSIX ACL and PATHNAMES if not set
3296 * originally at mount time
3298 if ((saved_cap & CIFS_UNIX_POSIX_ACL_CAP) == 0)
3299 cap &= ~CIFS_UNIX_POSIX_ACL_CAP;
3300 if ((saved_cap & CIFS_UNIX_POSIX_PATHNAMES_CAP) == 0) {
3301 if (cap & CIFS_UNIX_POSIX_PATHNAMES_CAP)
3302 cifs_dbg(VFS, "POSIXPATH support change\n");
3303 cap &= ~CIFS_UNIX_POSIX_PATHNAMES_CAP;
3304 } else if ((cap & CIFS_UNIX_POSIX_PATHNAMES_CAP) == 0) {
3305 cifs_dbg(VFS, "possible reconnect error\n");
3306 cifs_dbg(VFS, "server disabled POSIX path support\n");
3310 if (cap & CIFS_UNIX_TRANSPORT_ENCRYPTION_MANDATORY_CAP)
3311 cifs_dbg(VFS, "per-share encryption not supported yet\n");
3313 cap &= CIFS_UNIX_CAP_MASK;
3314 if (ctx && ctx->no_psx_acl)
3315 cap &= ~CIFS_UNIX_POSIX_ACL_CAP;
3316 else if (CIFS_UNIX_POSIX_ACL_CAP & cap) {
3317 cifs_dbg(FYI, "negotiated posix acl support\n");
3319 cifs_sb->mnt_cifs_flags |=
3320 CIFS_MOUNT_POSIXACL;
3323 if (ctx && ctx->posix_paths == 0)
3324 cap &= ~CIFS_UNIX_POSIX_PATHNAMES_CAP;
3325 else if (cap & CIFS_UNIX_POSIX_PATHNAMES_CAP) {
3326 cifs_dbg(FYI, "negotiate posix pathnames\n");
3328 cifs_sb->mnt_cifs_flags |=
3329 CIFS_MOUNT_POSIX_PATHS;
3332 cifs_dbg(FYI, "Negotiate caps 0x%x\n", (int)cap);
3333 #ifdef CONFIG_CIFS_DEBUG2
3334 if (cap & CIFS_UNIX_FCNTL_CAP)
3335 cifs_dbg(FYI, "FCNTL cap\n");
3336 if (cap & CIFS_UNIX_EXTATTR_CAP)
3337 cifs_dbg(FYI, "EXTATTR cap\n");
3338 if (cap & CIFS_UNIX_POSIX_PATHNAMES_CAP)
3339 cifs_dbg(FYI, "POSIX path cap\n");
3340 if (cap & CIFS_UNIX_XATTR_CAP)
3341 cifs_dbg(FYI, "XATTR cap\n");
3342 if (cap & CIFS_UNIX_POSIX_ACL_CAP)
3343 cifs_dbg(FYI, "POSIX ACL cap\n");
3344 if (cap & CIFS_UNIX_LARGE_READ_CAP)
3345 cifs_dbg(FYI, "very large read cap\n");
3346 if (cap & CIFS_UNIX_LARGE_WRITE_CAP)
3347 cifs_dbg(FYI, "very large write cap\n");
3348 if (cap & CIFS_UNIX_TRANSPORT_ENCRYPTION_CAP)
3349 cifs_dbg(FYI, "transport encryption cap\n");
3350 if (cap & CIFS_UNIX_TRANSPORT_ENCRYPTION_MANDATORY_CAP)
3351 cifs_dbg(FYI, "mandatory transport encryption cap\n");
3352 #endif /* CIFS_DEBUG2 */
3353 if (CIFSSMBSetFSUnixInfo(xid, tcon, cap)) {
3355 cifs_dbg(FYI, "resetting capabilities failed\n");
3357 cifs_dbg(VFS, "Negotiating Unix capabilities with the server failed. Consider mounting with the Unix Extensions disabled if problems are found by specifying the nounix mount option.\n");
3362 #endif /* CONFIG_CIFS_ALLOW_INSECURE_LEGACY */
3364 int cifs_setup_cifs_sb(struct cifs_sb_info *cifs_sb)
3366 struct smb3_fs_context *ctx = cifs_sb->ctx;
3368 INIT_DELAYED_WORK(&cifs_sb->prune_tlinks, cifs_prune_tlinks);
3370 spin_lock_init(&cifs_sb->tlink_tree_lock);
3371 cifs_sb->tlink_tree = RB_ROOT;
3373 cifs_dbg(FYI, "file mode: %04ho dir mode: %04ho\n",
3374 ctx->file_mode, ctx->dir_mode);
3376 /* this is needed for ASCII cp to Unicode converts */
3377 if (ctx->iocharset == NULL) {
3378 /* load_nls_default cannot return null */
3379 cifs_sb->local_nls = load_nls_default();
3381 cifs_sb->local_nls = load_nls(ctx->iocharset);
3382 if (cifs_sb->local_nls == NULL) {
3383 cifs_dbg(VFS, "CIFS mount error: iocharset %s not found\n",
3388 ctx->local_nls = cifs_sb->local_nls;
3390 smb3_update_mnt_flags(cifs_sb);
3393 cifs_dbg(FYI, "mounting share using direct i/o\n");
3394 if (ctx->cache_ro) {
3395 cifs_dbg(VFS, "mounting share with read only caching. Ensure that the share will not be modified while in use.\n");
3396 cifs_sb->mnt_cifs_flags |= CIFS_MOUNT_RO_CACHE;
3397 } else if (ctx->cache_rw) {
3398 cifs_dbg(VFS, "mounting share in single client RW caching mode. Ensure that no other systems will be accessing the share.\n");
3399 cifs_sb->mnt_cifs_flags |= (CIFS_MOUNT_RO_CACHE |
3400 CIFS_MOUNT_RW_CACHE);
3403 if ((ctx->cifs_acl) && (ctx->dynperm))
3404 cifs_dbg(VFS, "mount option dynperm ignored if cifsacl mount option supported\n");
3407 cifs_sb->prepath = kstrdup(ctx->prepath, GFP_KERNEL);
3408 if (cifs_sb->prepath == NULL)
3410 cifs_sb->mnt_cifs_flags |= CIFS_MOUNT_USE_PREFIX_PATH;
3416 /* Release all succeed connections */
3417 void cifs_mount_put_conns(struct cifs_mount_ctx *mnt_ctx)
3422 cifs_put_tcon(mnt_ctx->tcon, netfs_trace_tcon_ref_put_mnt_ctx);
3423 else if (mnt_ctx->ses)
3424 cifs_put_smb_ses(mnt_ctx->ses);
3425 else if (mnt_ctx->server)
3426 cifs_put_tcp_session(mnt_ctx->server, 0);
3427 mnt_ctx->ses = NULL;
3428 mnt_ctx->tcon = NULL;
3429 mnt_ctx->server = NULL;
3430 mnt_ctx->cifs_sb->mnt_cifs_flags &= ~CIFS_MOUNT_POSIX_PATHS;
3431 free_xid(mnt_ctx->xid);
3434 int cifs_mount_get_session(struct cifs_mount_ctx *mnt_ctx)
3436 struct TCP_Server_Info *server = NULL;
3437 struct smb3_fs_context *ctx;
3438 struct cifs_ses *ses = NULL;
3444 if (WARN_ON_ONCE(!mnt_ctx || !mnt_ctx->fs_ctx)) {
3448 ctx = mnt_ctx->fs_ctx;
3450 /* get a reference to a tcp session */
3451 server = cifs_get_tcp_session(ctx, NULL);
3452 if (IS_ERR(server)) {
3453 rc = PTR_ERR(server);
3458 /* get a reference to a SMB session */
3459 ses = cifs_get_smb_ses(server, ctx);
3466 if ((ctx->persistent == true) && (!(ses->server->capabilities &
3467 SMB2_GLOBAL_CAP_PERSISTENT_HANDLES))) {
3468 cifs_server_dbg(VFS, "persistent handles not supported by server\n");
3474 mnt_ctx->server = server;
3476 mnt_ctx->tcon = NULL;
3481 int cifs_mount_get_tcon(struct cifs_mount_ctx *mnt_ctx)
3483 struct TCP_Server_Info *server;
3484 struct cifs_sb_info *cifs_sb;
3485 struct smb3_fs_context *ctx;
3486 struct cifs_tcon *tcon = NULL;
3489 if (WARN_ON_ONCE(!mnt_ctx || !mnt_ctx->server || !mnt_ctx->ses || !mnt_ctx->fs_ctx ||
3490 !mnt_ctx->cifs_sb)) {
3494 server = mnt_ctx->server;
3495 ctx = mnt_ctx->fs_ctx;
3496 cifs_sb = mnt_ctx->cifs_sb;
3498 /* search for existing tcon to this server share */
3499 tcon = cifs_get_tcon(mnt_ctx->ses, ctx);
3506 /* if new SMB3.11 POSIX extensions are supported do not remap / and \ */
3507 if (tcon->posix_extensions)
3508 cifs_sb->mnt_cifs_flags |= CIFS_MOUNT_POSIX_PATHS;
3510 #ifdef CONFIG_CIFS_ALLOW_INSECURE_LEGACY
3511 /* tell server which Unix caps we support */
3512 if (cap_unix(tcon->ses)) {
3514 * reset of caps checks mount to see if unix extensions disabled
3515 * for just this mount.
3517 reset_cifs_unix_caps(mnt_ctx->xid, tcon, cifs_sb, ctx);
3518 spin_lock(&tcon->ses->server->srv_lock);
3519 if ((tcon->ses->server->tcpStatus == CifsNeedReconnect) &&
3520 (le64_to_cpu(tcon->fsUnixInfo.Capability) &
3521 CIFS_UNIX_TRANSPORT_ENCRYPTION_MANDATORY_CAP)) {
3522 spin_unlock(&tcon->ses->server->srv_lock);
3526 spin_unlock(&tcon->ses->server->srv_lock);
3528 #endif /* CONFIG_CIFS_ALLOW_INSECURE_LEGACY */
3529 tcon->unix_ext = 0; /* server does not support them */
3531 /* do not care if a following call succeed - informational */
3532 if (!tcon->pipe && server->ops->qfs_tcon) {
3533 server->ops->qfs_tcon(mnt_ctx->xid, tcon, cifs_sb);
3534 if (cifs_sb->mnt_cifs_flags & CIFS_MOUNT_RO_CACHE) {
3535 if (tcon->fsDevInfo.DeviceCharacteristics &
3536 cpu_to_le32(FILE_READ_ONLY_DEVICE))
3537 cifs_dbg(VFS, "mounted to read only share\n");
3538 else if ((cifs_sb->mnt_cifs_flags &
3539 CIFS_MOUNT_RW_CACHE) == 0)
3540 cifs_dbg(VFS, "read only mount of RW share\n");
3541 /* no need to log a RW mount of a typical RW share */
3546 * Clamp the rsize/wsize mount arguments if they are too big for the server
3547 * and set the rsize/wsize to the negotiated values if not passed in by
3550 if ((cifs_sb->ctx->wsize == 0) ||
3551 (cifs_sb->ctx->wsize > server->ops->negotiate_wsize(tcon, ctx))) {
3552 cifs_sb->ctx->wsize =
3553 round_down(server->ops->negotiate_wsize(tcon, ctx), PAGE_SIZE);
3555 * in the very unlikely event that the server sent a max write size under PAGE_SIZE,
3556 * (which would get rounded down to 0) then reset wsize to absolute minimum eg 4096
3558 if (cifs_sb->ctx->wsize == 0) {
3559 cifs_sb->ctx->wsize = PAGE_SIZE;
3560 cifs_dbg(VFS, "wsize too small, reset to minimum ie PAGE_SIZE, usually 4096\n");
3563 if ((cifs_sb->ctx->rsize == 0) ||
3564 (cifs_sb->ctx->rsize > server->ops->negotiate_rsize(tcon, ctx)))
3565 cifs_sb->ctx->rsize = server->ops->negotiate_rsize(tcon, ctx);
3568 * The cookie is initialized from volume info returned above.
3569 * Inside cifs_fscache_get_super_cookie it checks
3570 * that we do not get super cookie twice.
3572 if (cifs_sb->mnt_cifs_flags & CIFS_MOUNT_FSCACHE)
3573 cifs_fscache_get_super_cookie(tcon);
3576 mnt_ctx->tcon = tcon;
3580 static int mount_setup_tlink(struct cifs_sb_info *cifs_sb, struct cifs_ses *ses,
3581 struct cifs_tcon *tcon)
3583 struct tcon_link *tlink;
3585 /* hang the tcon off of the superblock */
3586 tlink = kzalloc(sizeof(*tlink), GFP_KERNEL);
3590 tlink->tl_uid = ses->linux_uid;
3591 tlink->tl_tcon = tcon;
3592 tlink->tl_time = jiffies;
3593 set_bit(TCON_LINK_MASTER, &tlink->tl_flags);
3594 set_bit(TCON_LINK_IN_TREE, &tlink->tl_flags);
3596 cifs_sb->master_tlink = tlink;
3597 spin_lock(&cifs_sb->tlink_tree_lock);
3598 tlink_rb_insert(&cifs_sb->tlink_tree, tlink);
3599 spin_unlock(&cifs_sb->tlink_tree_lock);
3601 queue_delayed_work(cifsiod_wq, &cifs_sb->prune_tlinks,
3607 cifs_are_all_path_components_accessible(struct TCP_Server_Info *server,
3609 struct cifs_tcon *tcon,
3610 struct cifs_sb_info *cifs_sb,
3617 int skip = added_treename ? 1 : 0;
3619 sep = CIFS_DIR_SEP(cifs_sb);
3622 rc = server->ops->is_path_accessible(xid, tcon, cifs_sb, "");
3624 /* skip separators */
3629 /* next separator */
3630 while (*s && *s != sep)
3633 * if the treename is added, we then have to skip the first
3634 * part within the separators
3641 * temporarily null-terminate the path at the end of
3642 * the current component
3646 rc = server->ops->is_path_accessible(xid, tcon, cifs_sb,
3654 * Check if path is remote (i.e. a DFS share).
3656 * Return -EREMOTE if it is, otherwise 0 or -errno.
3658 int cifs_is_path_remote(struct cifs_mount_ctx *mnt_ctx)
3661 struct cifs_sb_info *cifs_sb = mnt_ctx->cifs_sb;
3662 struct TCP_Server_Info *server = mnt_ctx->server;
3663 unsigned int xid = mnt_ctx->xid;
3664 struct cifs_tcon *tcon = mnt_ctx->tcon;
3665 struct smb3_fs_context *ctx = mnt_ctx->fs_ctx;
3668 if (!server->ops->is_path_accessible)
3672 * cifs_build_path_to_root works only when we have a valid tcon
3674 full_path = cifs_build_path_to_root(ctx, cifs_sb, tcon,
3675 tcon->Flags & SMB_SHARE_IS_IN_DFS);
3676 if (full_path == NULL)
3679 cifs_dbg(FYI, "%s: full_path: %s\n", __func__, full_path);
3681 rc = server->ops->is_path_accessible(xid, tcon, cifs_sb,
3683 if (rc != 0 && rc != -EREMOTE)
3686 if (rc != -EREMOTE) {
3687 rc = cifs_are_all_path_components_accessible(server, xid, tcon,
3688 cifs_sb, full_path, tcon->Flags & SMB_SHARE_IS_IN_DFS);
3690 cifs_server_dbg(VFS, "cannot query dirs between root and final path, enabling CIFS_MOUNT_USE_PREFIX_PATH\n");
3691 cifs_sb->mnt_cifs_flags |= CIFS_MOUNT_USE_PREFIX_PATH;
3701 #ifdef CONFIG_CIFS_DFS_UPCALL
3702 int cifs_mount(struct cifs_sb_info *cifs_sb, struct smb3_fs_context *ctx)
3704 struct cifs_mount_ctx mnt_ctx = { .cifs_sb = cifs_sb, .fs_ctx = ctx, };
3707 rc = dfs_mount_share(&mnt_ctx);
3714 * After reconnecting to a different server, unique ids won't match anymore, so we disable
3715 * serverino. This prevents dentry revalidation to think the dentry are stale (ESTALE).
3717 cifs_autodisable_serverino(cifs_sb);
3719 * Force the use of prefix path to support failover on DFS paths that resolve to targets
3720 * that have different prefix paths.
3722 cifs_sb->mnt_cifs_flags |= CIFS_MOUNT_USE_PREFIX_PATH;
3723 kfree(cifs_sb->prepath);
3724 cifs_sb->prepath = ctx->prepath;
3725 ctx->prepath = NULL;
3728 cifs_try_adding_channels(mnt_ctx.ses);
3729 rc = mount_setup_tlink(cifs_sb, mnt_ctx.ses, mnt_ctx.tcon);
3733 free_xid(mnt_ctx.xid);
3737 cifs_mount_put_conns(&mnt_ctx);
3741 int cifs_mount(struct cifs_sb_info *cifs_sb, struct smb3_fs_context *ctx)
3744 struct cifs_mount_ctx mnt_ctx = { .cifs_sb = cifs_sb, .fs_ctx = ctx, };
3746 rc = cifs_mount_get_session(&mnt_ctx);
3750 rc = cifs_mount_get_tcon(&mnt_ctx);
3753 * Prevent superblock from being created with any missing
3756 if (WARN_ON(!mnt_ctx.server))
3758 else if (WARN_ON(!mnt_ctx.ses))
3760 else if (WARN_ON(!mnt_ctx.tcon))
3766 rc = cifs_is_path_remote(&mnt_ctx);
3772 rc = mount_setup_tlink(cifs_sb, mnt_ctx.ses, mnt_ctx.tcon);
3776 free_xid(mnt_ctx.xid);
3780 cifs_mount_put_conns(&mnt_ctx);
3785 #ifdef CONFIG_CIFS_ALLOW_INSECURE_LEGACY
3787 * Issue a TREE_CONNECT request.
3790 CIFSTCon(const unsigned int xid, struct cifs_ses *ses,
3791 const char *tree, struct cifs_tcon *tcon,
3792 const struct nls_table *nls_codepage)
3794 struct smb_hdr *smb_buffer;
3795 struct smb_hdr *smb_buffer_response;
3798 unsigned char *bcc_ptr;
3801 __u16 bytes_left, count;
3806 smb_buffer = cifs_buf_get();
3807 if (smb_buffer == NULL)
3810 smb_buffer_response = smb_buffer;
3812 header_assemble(smb_buffer, SMB_COM_TREE_CONNECT_ANDX,
3813 NULL /*no tid */, 4 /*wct */);
3815 smb_buffer->Mid = get_next_mid(ses->server);
3816 smb_buffer->Uid = ses->Suid;
3817 pSMB = (TCONX_REQ *) smb_buffer;
3818 pSMBr = (TCONX_RSP *) smb_buffer_response;
3820 pSMB->AndXCommand = 0xFF;
3821 pSMB->Flags = cpu_to_le16(TCON_EXTENDED_SECINFO);
3822 bcc_ptr = &pSMB->Password[0];
3824 pSMB->PasswordLength = cpu_to_le16(1); /* minimum */
3825 *bcc_ptr = 0; /* password is null byte */
3826 bcc_ptr++; /* skip password */
3827 /* already aligned so no need to do it below */
3829 if (ses->server->sign)
3830 smb_buffer->Flags2 |= SMBFLG2_SECURITY_SIGNATURE;
3832 if (ses->capabilities & CAP_STATUS32)
3833 smb_buffer->Flags2 |= SMBFLG2_ERR_STATUS;
3835 if (ses->capabilities & CAP_DFS)
3836 smb_buffer->Flags2 |= SMBFLG2_DFS;
3838 if (ses->capabilities & CAP_UNICODE) {
3839 smb_buffer->Flags2 |= SMBFLG2_UNICODE;
3841 cifs_strtoUTF16((__le16 *) bcc_ptr, tree,
3842 6 /* max utf8 char length in bytes */ *
3843 (/* server len*/ + 256 /* share len */), nls_codepage);
3844 bcc_ptr += 2 * length; /* convert num 16 bit words to bytes */
3845 bcc_ptr += 2; /* skip trailing null */
3846 } else { /* ASCII */
3847 strcpy(bcc_ptr, tree);
3848 bcc_ptr += strlen(tree) + 1;
3850 strcpy(bcc_ptr, "?????");
3851 bcc_ptr += strlen("?????");
3853 count = bcc_ptr - &pSMB->Password[0];
3854 be32_add_cpu(&pSMB->hdr.smb_buf_length, count);
3855 pSMB->ByteCount = cpu_to_le16(count);
3857 rc = SendReceive(xid, ses, smb_buffer, smb_buffer_response, &length,
3860 /* above now done in SendReceive */
3864 tcon->tid = smb_buffer_response->Tid;
3865 bcc_ptr = pByteArea(smb_buffer_response);
3866 bytes_left = get_bcc(smb_buffer_response);
3867 length = strnlen(bcc_ptr, bytes_left - 2);
3868 if (smb_buffer->Flags2 & SMBFLG2_UNICODE)
3874 /* skip service field (NB: this field is always ASCII) */
3876 if ((bcc_ptr[0] == 'I') && (bcc_ptr[1] == 'P') &&
3877 (bcc_ptr[2] == 'C')) {
3878 cifs_dbg(FYI, "IPC connection\n");
3882 } else if (length == 2) {
3883 if ((bcc_ptr[0] == 'A') && (bcc_ptr[1] == ':')) {
3884 /* the most common case */
3885 cifs_dbg(FYI, "disk share connection\n");
3888 bcc_ptr += length + 1;
3889 bytes_left -= (length + 1);
3890 strscpy(tcon->tree_name, tree, sizeof(tcon->tree_name));
3892 /* mostly informational -- no need to fail on error here */
3893 kfree(tcon->nativeFileSystem);
3894 tcon->nativeFileSystem = cifs_strndup_from_utf16(bcc_ptr,
3895 bytes_left, is_unicode,
3898 cifs_dbg(FYI, "nativeFileSystem=%s\n", tcon->nativeFileSystem);
3900 if ((smb_buffer_response->WordCount == 3) ||
3901 (smb_buffer_response->WordCount == 7))
3902 /* field is in same location */
3903 tcon->Flags = le16_to_cpu(pSMBr->OptionalSupport);
3906 cifs_dbg(FYI, "Tcon flags: 0x%x\n", tcon->Flags);
3909 * reset_cifs_unix_caps calls QFSInfo which requires
3910 * need_reconnect to be false, but we would not need to call
3911 * reset_caps if this were not a reconnect case so must check
3912 * need_reconnect flag here. The caller will also clear
3913 * need_reconnect when tcon was successful but needed to be
3914 * cleared earlier in the case of unix extensions reconnect
3916 if (tcon->need_reconnect && tcon->unix_ext) {
3917 cifs_dbg(FYI, "resetting caps for %s\n", tcon->tree_name);
3918 tcon->need_reconnect = false;
3919 reset_cifs_unix_caps(xid, tcon, NULL, NULL);
3922 cifs_buf_release(smb_buffer);
3925 #endif /* CONFIG_CIFS_ALLOW_INSECURE_LEGACY */
3927 static void delayed_free(struct rcu_head *p)
3929 struct cifs_sb_info *cifs_sb = container_of(p, struct cifs_sb_info, rcu);
3931 unload_nls(cifs_sb->local_nls);
3932 smb3_cleanup_fs_context(cifs_sb->ctx);
3937 cifs_umount(struct cifs_sb_info *cifs_sb)
3939 struct rb_root *root = &cifs_sb->tlink_tree;
3940 struct rb_node *node;
3941 struct tcon_link *tlink;
3943 cancel_delayed_work_sync(&cifs_sb->prune_tlinks);
3945 spin_lock(&cifs_sb->tlink_tree_lock);
3946 while ((node = rb_first(root))) {
3947 tlink = rb_entry(node, struct tcon_link, tl_rbnode);
3948 cifs_get_tlink(tlink);
3949 clear_bit(TCON_LINK_IN_TREE, &tlink->tl_flags);
3950 rb_erase(node, root);
3952 spin_unlock(&cifs_sb->tlink_tree_lock);
3953 cifs_put_tlink(tlink);
3954 spin_lock(&cifs_sb->tlink_tree_lock);
3956 spin_unlock(&cifs_sb->tlink_tree_lock);
3958 kfree(cifs_sb->prepath);
3959 call_rcu(&cifs_sb->rcu, delayed_free);
3963 cifs_negotiate_protocol(const unsigned int xid, struct cifs_ses *ses,
3964 struct TCP_Server_Info *server)
3968 if (!server->ops->need_neg || !server->ops->negotiate)
3971 /* only send once per connect */
3972 spin_lock(&server->srv_lock);
3973 if (server->tcpStatus != CifsGood &&
3974 server->tcpStatus != CifsNew &&
3975 server->tcpStatus != CifsNeedNegotiate) {
3976 spin_unlock(&server->srv_lock);
3980 if (!server->ops->need_neg(server) &&
3981 server->tcpStatus == CifsGood) {
3982 spin_unlock(&server->srv_lock);
3986 server->tcpStatus = CifsInNegotiate;
3987 spin_unlock(&server->srv_lock);
3989 rc = server->ops->negotiate(xid, ses, server);
3991 spin_lock(&server->srv_lock);
3992 if (server->tcpStatus == CifsInNegotiate)
3993 server->tcpStatus = CifsGood;
3996 spin_unlock(&server->srv_lock);
3998 spin_lock(&server->srv_lock);
3999 if (server->tcpStatus == CifsInNegotiate)
4000 server->tcpStatus = CifsNeedNegotiate;
4001 spin_unlock(&server->srv_lock);
4008 cifs_setup_session(const unsigned int xid, struct cifs_ses *ses,
4009 struct TCP_Server_Info *server,
4010 struct nls_table *nls_info)
4013 struct TCP_Server_Info *pserver = SERVER_IS_CHAN(server) ? server->primary_server : server;
4014 struct sockaddr_in6 *addr6 = (struct sockaddr_in6 *)&pserver->dstaddr;
4015 struct sockaddr_in *addr = (struct sockaddr_in *)&pserver->dstaddr;
4016 bool is_binding = false;
4018 spin_lock(&ses->ses_lock);
4019 cifs_dbg(FYI, "%s: channel connect bitmap: 0x%lx\n",
4020 __func__, ses->chans_need_reconnect);
4022 if (ses->ses_status != SES_GOOD &&
4023 ses->ses_status != SES_NEW &&
4024 ses->ses_status != SES_NEED_RECON) {
4025 spin_unlock(&ses->ses_lock);
4029 /* only send once per connect */
4030 spin_lock(&ses->chan_lock);
4031 if (CIFS_ALL_CHANS_GOOD(ses)) {
4032 if (ses->ses_status == SES_NEED_RECON)
4033 ses->ses_status = SES_GOOD;
4034 spin_unlock(&ses->chan_lock);
4035 spin_unlock(&ses->ses_lock);
4039 cifs_chan_set_in_reconnect(ses, server);
4040 is_binding = !CIFS_ALL_CHANS_NEED_RECONNECT(ses);
4041 spin_unlock(&ses->chan_lock);
4044 ses->ses_status = SES_IN_SETUP;
4046 /* force iface_list refresh */
4047 ses->iface_last_update = 0;
4049 spin_unlock(&ses->ses_lock);
4051 /* update ses ip_addr only for primary chan */
4052 if (server == pserver) {
4053 if (server->dstaddr.ss_family == AF_INET6)
4054 scnprintf(ses->ip_addr, sizeof(ses->ip_addr), "%pI6", &addr6->sin6_addr);
4056 scnprintf(ses->ip_addr, sizeof(ses->ip_addr), "%pI4", &addr->sin_addr);
4060 ses->capabilities = server->capabilities;
4061 if (!linuxExtEnabled)
4062 ses->capabilities &= (~server->vals->cap_unix);
4064 if (ses->auth_key.response) {
4065 cifs_dbg(FYI, "Free previous auth_key.response = %p\n",
4066 ses->auth_key.response);
4067 kfree_sensitive(ses->auth_key.response);
4068 ses->auth_key.response = NULL;
4069 ses->auth_key.len = 0;
4073 cifs_dbg(FYI, "Security Mode: 0x%x Capabilities: 0x%x TimeAdjust: %d\n",
4074 server->sec_mode, server->capabilities, server->timeAdj);
4076 if (server->ops->sess_setup)
4077 rc = server->ops->sess_setup(xid, ses, server, nls_info);
4080 cifs_server_dbg(VFS, "Send error in SessSetup = %d\n", rc);
4081 spin_lock(&ses->ses_lock);
4082 if (ses->ses_status == SES_IN_SETUP)
4083 ses->ses_status = SES_NEED_RECON;
4084 spin_lock(&ses->chan_lock);
4085 cifs_chan_clear_in_reconnect(ses, server);
4086 spin_unlock(&ses->chan_lock);
4087 spin_unlock(&ses->ses_lock);
4089 spin_lock(&ses->ses_lock);
4090 if (ses->ses_status == SES_IN_SETUP)
4091 ses->ses_status = SES_GOOD;
4092 spin_lock(&ses->chan_lock);
4093 cifs_chan_clear_in_reconnect(ses, server);
4094 cifs_chan_clear_need_reconnect(ses, server);
4095 spin_unlock(&ses->chan_lock);
4096 spin_unlock(&ses->ses_lock);
4103 cifs_set_vol_auth(struct smb3_fs_context *ctx, struct cifs_ses *ses)
4105 ctx->sectype = ses->sectype;
4107 /* krb5 is special, since we don't need username or pw */
4108 if (ctx->sectype == Kerberos)
4111 return cifs_set_cifscreds(ctx, ses);
4114 static struct cifs_tcon *
4115 cifs_construct_tcon(struct cifs_sb_info *cifs_sb, kuid_t fsuid)
4118 struct cifs_tcon *master_tcon = cifs_sb_master_tcon(cifs_sb);
4119 struct cifs_ses *ses;
4120 struct cifs_tcon *tcon = NULL;
4121 struct smb3_fs_context *ctx;
4122 char *origin_fullpath = NULL;
4124 ctx = kzalloc(sizeof(*ctx), GFP_KERNEL);
4126 return ERR_PTR(-ENOMEM);
4128 ctx->local_nls = cifs_sb->local_nls;
4129 ctx->linux_uid = fsuid;
4130 ctx->cred_uid = fsuid;
4131 ctx->UNC = master_tcon->tree_name;
4132 ctx->retry = master_tcon->retry;
4133 ctx->nocase = master_tcon->nocase;
4134 ctx->nohandlecache = master_tcon->nohandlecache;
4135 ctx->local_lease = master_tcon->local_lease;
4136 ctx->no_lease = master_tcon->no_lease;
4137 ctx->resilient = master_tcon->use_resilient;
4138 ctx->persistent = master_tcon->use_persistent;
4139 ctx->handle_timeout = master_tcon->handle_timeout;
4140 ctx->no_linux_ext = !master_tcon->unix_ext;
4141 ctx->linux_ext = master_tcon->posix_extensions;
4142 ctx->sectype = master_tcon->ses->sectype;
4143 ctx->sign = master_tcon->ses->sign;
4144 ctx->seal = master_tcon->seal;
4145 ctx->witness = master_tcon->use_witness;
4146 ctx->dfs_root_ses = master_tcon->ses->dfs_root_ses;
4148 rc = cifs_set_vol_auth(ctx, master_tcon->ses);
4154 /* get a reference for the same TCP session */
4155 spin_lock(&cifs_tcp_ses_lock);
4156 ++master_tcon->ses->server->srv_count;
4157 spin_unlock(&cifs_tcp_ses_lock);
4159 ses = cifs_get_smb_ses(master_tcon->ses->server, ctx);
4161 tcon = ERR_CAST(ses);
4162 cifs_put_tcp_session(master_tcon->ses->server, 0);
4166 #ifdef CONFIG_CIFS_DFS_UPCALL
4167 spin_lock(&master_tcon->tc_lock);
4168 if (master_tcon->origin_fullpath) {
4169 spin_unlock(&master_tcon->tc_lock);
4170 origin_fullpath = dfs_get_path(cifs_sb, cifs_sb->ctx->source);
4171 if (IS_ERR(origin_fullpath)) {
4172 tcon = ERR_CAST(origin_fullpath);
4173 origin_fullpath = NULL;
4174 cifs_put_smb_ses(ses);
4178 spin_unlock(&master_tcon->tc_lock);
4182 tcon = cifs_get_tcon(ses, ctx);
4184 cifs_put_smb_ses(ses);
4188 #ifdef CONFIG_CIFS_DFS_UPCALL
4189 if (origin_fullpath) {
4190 spin_lock(&tcon->tc_lock);
4191 tcon->origin_fullpath = origin_fullpath;
4192 spin_unlock(&tcon->tc_lock);
4193 origin_fullpath = NULL;
4194 queue_delayed_work(dfscache_wq, &tcon->dfs_cache_work,
4195 dfs_cache_get_ttl() * HZ);
4199 #ifdef CONFIG_CIFS_ALLOW_INSECURE_LEGACY
4201 reset_cifs_unix_caps(0, tcon, NULL, ctx);
4202 #endif /* CONFIG_CIFS_ALLOW_INSECURE_LEGACY */
4205 kfree(ctx->username);
4206 kfree_sensitive(ctx->password);
4207 kfree(origin_fullpath);
4214 cifs_sb_master_tcon(struct cifs_sb_info *cifs_sb)
4216 return tlink_tcon(cifs_sb_master_tlink(cifs_sb));
4219 /* find and return a tlink with given uid */
4220 static struct tcon_link *
4221 tlink_rb_search(struct rb_root *root, kuid_t uid)
4223 struct rb_node *node = root->rb_node;
4224 struct tcon_link *tlink;
4227 tlink = rb_entry(node, struct tcon_link, tl_rbnode);
4229 if (uid_gt(tlink->tl_uid, uid))
4230 node = node->rb_left;
4231 else if (uid_lt(tlink->tl_uid, uid))
4232 node = node->rb_right;
4239 /* insert a tcon_link into the tree */
4241 tlink_rb_insert(struct rb_root *root, struct tcon_link *new_tlink)
4243 struct rb_node **new = &(root->rb_node), *parent = NULL;
4244 struct tcon_link *tlink;
4247 tlink = rb_entry(*new, struct tcon_link, tl_rbnode);
4250 if (uid_gt(tlink->tl_uid, new_tlink->tl_uid))
4251 new = &((*new)->rb_left);
4253 new = &((*new)->rb_right);
4256 rb_link_node(&new_tlink->tl_rbnode, parent, new);
4257 rb_insert_color(&new_tlink->tl_rbnode, root);
4261 * Find or construct an appropriate tcon given a cifs_sb and the fsuid of the
4264 * If the superblock doesn't refer to a multiuser mount, then just return
4265 * the master tcon for the mount.
4267 * First, search the rbtree for an existing tcon for this fsuid. If one
4268 * exists, then check to see if it's pending construction. If it is then wait
4269 * for construction to complete. Once it's no longer pending, check to see if
4270 * it failed and either return an error or retry construction, depending on
4273 * If one doesn't exist then insert a new tcon_link struct into the tree and
4274 * try to construct a new one.
4276 * REMEMBER to call cifs_put_tlink() after successful calls to cifs_sb_tlink,
4277 * to avoid refcount issues
4280 cifs_sb_tlink(struct cifs_sb_info *cifs_sb)
4282 struct tcon_link *tlink, *newtlink;
4283 kuid_t fsuid = current_fsuid();
4286 if (!(cifs_sb->mnt_cifs_flags & CIFS_MOUNT_MULTIUSER))
4287 return cifs_get_tlink(cifs_sb_master_tlink(cifs_sb));
4289 spin_lock(&cifs_sb->tlink_tree_lock);
4290 tlink = tlink_rb_search(&cifs_sb->tlink_tree, fsuid);
4292 cifs_get_tlink(tlink);
4293 spin_unlock(&cifs_sb->tlink_tree_lock);
4295 if (tlink == NULL) {
4296 newtlink = kzalloc(sizeof(*tlink), GFP_KERNEL);
4297 if (newtlink == NULL)
4298 return ERR_PTR(-ENOMEM);
4299 newtlink->tl_uid = fsuid;
4300 newtlink->tl_tcon = ERR_PTR(-EACCES);
4301 set_bit(TCON_LINK_PENDING, &newtlink->tl_flags);
4302 set_bit(TCON_LINK_IN_TREE, &newtlink->tl_flags);
4303 cifs_get_tlink(newtlink);
4305 spin_lock(&cifs_sb->tlink_tree_lock);
4306 /* was one inserted after previous search? */
4307 tlink = tlink_rb_search(&cifs_sb->tlink_tree, fsuid);
4309 cifs_get_tlink(tlink);
4310 spin_unlock(&cifs_sb->tlink_tree_lock);
4312 goto wait_for_construction;
4315 tlink_rb_insert(&cifs_sb->tlink_tree, tlink);
4316 spin_unlock(&cifs_sb->tlink_tree_lock);
4318 wait_for_construction:
4319 err = wait_on_bit(&tlink->tl_flags, TCON_LINK_PENDING,
4320 TASK_INTERRUPTIBLE);
4322 cifs_put_tlink(tlink);
4323 return ERR_PTR(-ERESTARTSYS);
4326 /* if it's good, return it */
4327 if (!IS_ERR(tlink->tl_tcon))
4330 /* return error if we tried this already recently */
4331 if (time_before(jiffies, tlink->tl_time + TLINK_ERROR_EXPIRE)) {
4332 err = PTR_ERR(tlink->tl_tcon);
4333 cifs_put_tlink(tlink);
4334 return ERR_PTR(err);
4337 if (test_and_set_bit(TCON_LINK_PENDING, &tlink->tl_flags))
4338 goto wait_for_construction;
4341 tlink->tl_tcon = cifs_construct_tcon(cifs_sb, fsuid);
4342 clear_bit(TCON_LINK_PENDING, &tlink->tl_flags);
4343 wake_up_bit(&tlink->tl_flags, TCON_LINK_PENDING);
4345 if (IS_ERR(tlink->tl_tcon)) {
4346 err = PTR_ERR(tlink->tl_tcon);
4349 cifs_put_tlink(tlink);
4350 return ERR_PTR(err);
4357 * periodic workqueue job that scans tcon_tree for a superblock and closes
4361 cifs_prune_tlinks(struct work_struct *work)
4363 struct cifs_sb_info *cifs_sb = container_of(work, struct cifs_sb_info,
4365 struct rb_root *root = &cifs_sb->tlink_tree;
4366 struct rb_node *node;
4367 struct rb_node *tmp;
4368 struct tcon_link *tlink;
4371 * Because we drop the spinlock in the loop in order to put the tlink
4372 * it's not guarded against removal of links from the tree. The only
4373 * places that remove entries from the tree are this function and
4374 * umounts. Because this function is non-reentrant and is canceled
4375 * before umount can proceed, this is safe.
4377 spin_lock(&cifs_sb->tlink_tree_lock);
4378 node = rb_first(root);
4379 while (node != NULL) {
4381 node = rb_next(tmp);
4382 tlink = rb_entry(tmp, struct tcon_link, tl_rbnode);
4384 if (test_bit(TCON_LINK_MASTER, &tlink->tl_flags) ||
4385 atomic_read(&tlink->tl_count) != 0 ||
4386 time_after(tlink->tl_time + TLINK_IDLE_EXPIRE, jiffies))
4389 cifs_get_tlink(tlink);
4390 clear_bit(TCON_LINK_IN_TREE, &tlink->tl_flags);
4391 rb_erase(tmp, root);
4393 spin_unlock(&cifs_sb->tlink_tree_lock);
4394 cifs_put_tlink(tlink);
4395 spin_lock(&cifs_sb->tlink_tree_lock);
4397 spin_unlock(&cifs_sb->tlink_tree_lock);
4399 queue_delayed_work(cifsiod_wq, &cifs_sb->prune_tlinks,
4403 #ifndef CONFIG_CIFS_DFS_UPCALL
4404 int cifs_tree_connect(const unsigned int xid, struct cifs_tcon *tcon)
4406 const struct smb_version_operations *ops = tcon->ses->server->ops;
4409 /* only send once per connect */
4410 spin_lock(&tcon->tc_lock);
4412 /* if tcon is marked for needing reconnect, update state */
4413 if (tcon->need_reconnect)
4414 tcon->status = TID_NEED_TCON;
4416 if (tcon->status == TID_GOOD) {
4417 spin_unlock(&tcon->tc_lock);
4421 if (tcon->status != TID_NEW &&
4422 tcon->status != TID_NEED_TCON) {
4423 spin_unlock(&tcon->tc_lock);
4427 tcon->status = TID_IN_TCON;
4428 spin_unlock(&tcon->tc_lock);
4430 rc = ops->tree_connect(xid, tcon->ses, tcon->tree_name,
4431 tcon, tcon->ses->local_nls);
4433 spin_lock(&tcon->tc_lock);
4434 if (tcon->status == TID_IN_TCON)
4435 tcon->status = TID_NEED_TCON;
4436 spin_unlock(&tcon->tc_lock);
4438 spin_lock(&tcon->tc_lock);
4439 if (tcon->status == TID_IN_TCON)
4440 tcon->status = TID_GOOD;
4441 tcon->need_reconnect = false;
4442 spin_unlock(&tcon->tc_lock);