1 // SPDX-License-Identifier: LGPL-2.1
4 * Copyright (C) International Business Machines Corp., 2002,2011
5 * Author(s): Steve French (sfrench@us.ibm.com)
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 extern mempool_t *cifs_req_poolp;
56 extern bool disable_legacy_dialects;
58 /* FIXME: should these be tunable? */
59 #define TLINK_ERROR_EXPIRE (1 * HZ)
60 #define TLINK_IDLE_EXPIRE (600 * HZ)
62 /* Drop the connection to not overload the server */
63 #define MAX_STATUS_IO_TIMEOUT 5
65 static int ip_connect(struct TCP_Server_Info *server);
66 static int generic_ip_connect(struct TCP_Server_Info *server);
67 static void tlink_rb_insert(struct rb_root *root, struct tcon_link *new_tlink);
68 static void cifs_prune_tlinks(struct work_struct *work);
71 * Resolve hostname and set ip addr in tcp ses. Useful for hostnames that may
72 * get their ip addresses changed at some point.
74 * This should be called with server->srv_mutex held.
76 static int reconn_set_ipaddr_from_hostname(struct TCP_Server_Info *server)
81 struct sockaddr_storage ss;
83 if (!server->hostname)
86 /* if server hostname isn't populated, there's nothing to do here */
87 if (server->hostname[0] == '\0')
90 len = strlen(server->hostname) + 3;
92 unc = kmalloc(len, GFP_KERNEL);
94 cifs_dbg(FYI, "%s: failed to create UNC path\n", __func__);
97 scnprintf(unc, len, "\\\\%s", server->hostname);
99 spin_lock(&server->srv_lock);
100 ss = server->dstaddr;
101 spin_unlock(&server->srv_lock);
103 rc = dns_resolve_server_name_to_ip(unc, (struct sockaddr *)&ss, NULL);
107 cifs_dbg(FYI, "%s: failed to resolve server part of %s to IP: %d\n",
108 __func__, server->hostname, rc);
110 spin_lock(&server->srv_lock);
111 memcpy(&server->dstaddr, &ss, sizeof(server->dstaddr));
112 spin_unlock(&server->srv_lock);
119 static void smb2_query_server_interfaces(struct work_struct *work)
122 struct cifs_tcon *tcon = container_of(work,
124 query_interfaces.work);
127 * query server network interfaces, in case they change
129 rc = SMB3_request_interfaces(0, tcon, false);
131 if (rc == -EOPNOTSUPP)
134 cifs_dbg(FYI, "%s: failed to query server interfaces: %d\n",
138 queue_delayed_work(cifsiod_wq, &tcon->query_interfaces,
139 (SMB_INTERFACE_POLL_INTERVAL * HZ));
143 * Update the tcpStatus for the server.
144 * This is used to signal the cifsd thread to call cifs_reconnect
145 * ONLY cifsd thread should call cifs_reconnect. For any other
146 * thread, use this function
148 * @server: the tcp ses for which reconnect is needed
149 * @all_channels: if this needs to be done for all channels
152 cifs_signal_cifsd_for_reconnect(struct TCP_Server_Info *server,
155 struct TCP_Server_Info *pserver;
156 struct cifs_ses *ses;
159 /* If server is a channel, select the primary channel */
160 pserver = SERVER_IS_CHAN(server) ? server->primary_server : server;
162 /* if we need to signal just this channel */
164 spin_lock(&server->srv_lock);
165 if (server->tcpStatus != CifsExiting)
166 server->tcpStatus = CifsNeedReconnect;
167 spin_unlock(&server->srv_lock);
171 spin_lock(&cifs_tcp_ses_lock);
172 list_for_each_entry(ses, &pserver->smb_ses_list, smb_ses_list) {
173 spin_lock(&ses->chan_lock);
174 for (i = 0; i < ses->chan_count; i++) {
175 if (!ses->chans[i].server)
178 spin_lock(&ses->chans[i].server->srv_lock);
179 if (ses->chans[i].server->tcpStatus != CifsExiting)
180 ses->chans[i].server->tcpStatus = CifsNeedReconnect;
181 spin_unlock(&ses->chans[i].server->srv_lock);
183 spin_unlock(&ses->chan_lock);
185 spin_unlock(&cifs_tcp_ses_lock);
189 * Mark all sessions and tcons for reconnect.
190 * IMPORTANT: make sure that this gets called only from
191 * cifsd thread. For any other thread, use
192 * cifs_signal_cifsd_for_reconnect
194 * @server: the tcp ses for which reconnect is needed
195 * @server needs to be previously set to CifsNeedReconnect.
196 * @mark_smb_session: whether even sessions need to be marked
199 cifs_mark_tcp_ses_conns_for_reconnect(struct TCP_Server_Info *server,
200 bool mark_smb_session)
202 struct TCP_Server_Info *pserver;
203 struct cifs_ses *ses, *nses;
204 struct cifs_tcon *tcon;
207 * before reconnecting the tcp session, mark the smb session (uid) and the tid bad so they
208 * are not used until reconnected.
210 cifs_dbg(FYI, "%s: marking necessary sessions and tcons for reconnect\n", __func__);
212 /* If server is a channel, select the primary channel */
213 pserver = SERVER_IS_CHAN(server) ? server->primary_server : server;
216 * if the server has been marked for termination, there is a
217 * chance that the remaining channels all need reconnect. To be
218 * on the safer side, mark the session and trees for reconnect
219 * for this scenario. This might cause a few redundant session
220 * setup and tree connect requests, but it is better than not doing
221 * a tree connect when needed, and all following requests failing
223 if (server->terminate) {
224 mark_smb_session = true;
228 spin_lock(&cifs_tcp_ses_lock);
229 list_for_each_entry_safe(ses, nses, &pserver->smb_ses_list, smb_ses_list) {
230 /* check if iface is still active */
231 spin_lock(&ses->chan_lock);
232 if (!cifs_chan_is_iface_active(ses, server)) {
233 spin_unlock(&ses->chan_lock);
234 cifs_chan_update_iface(ses, server);
235 spin_lock(&ses->chan_lock);
238 if (!mark_smb_session && cifs_chan_needs_reconnect(ses, server)) {
239 spin_unlock(&ses->chan_lock);
243 if (mark_smb_session)
244 CIFS_SET_ALL_CHANS_NEED_RECONNECT(ses);
246 cifs_chan_set_need_reconnect(ses, server);
248 cifs_dbg(FYI, "%s: channel connect bitmap: 0x%lx\n",
249 __func__, ses->chans_need_reconnect);
251 /* If all channels need reconnect, then tcon needs reconnect */
252 if (!mark_smb_session && !CIFS_ALL_CHANS_NEED_RECONNECT(ses)) {
253 spin_unlock(&ses->chan_lock);
256 spin_unlock(&ses->chan_lock);
258 spin_lock(&ses->ses_lock);
259 ses->ses_status = SES_NEED_RECON;
260 spin_unlock(&ses->ses_lock);
262 list_for_each_entry(tcon, &ses->tcon_list, tcon_list) {
263 tcon->need_reconnect = true;
264 spin_lock(&tcon->tc_lock);
265 tcon->status = TID_NEED_RECON;
266 spin_unlock(&tcon->tc_lock);
268 cancel_delayed_work(&tcon->query_interfaces);
271 ses->tcon_ipc->need_reconnect = true;
272 spin_lock(&ses->tcon_ipc->tc_lock);
273 ses->tcon_ipc->status = TID_NEED_RECON;
274 spin_unlock(&ses->tcon_ipc->tc_lock);
277 spin_unlock(&cifs_tcp_ses_lock);
281 cifs_abort_connection(struct TCP_Server_Info *server)
283 struct mid_q_entry *mid, *nmid;
284 struct list_head retry_list;
287 server->max_read = 0;
289 /* do not want to be sending data on a socket we are freeing */
290 cifs_dbg(FYI, "%s: tearing down socket\n", __func__);
291 cifs_server_lock(server);
292 if (server->ssocket) {
293 cifs_dbg(FYI, "State: 0x%x Flags: 0x%lx\n", server->ssocket->state,
294 server->ssocket->flags);
295 kernel_sock_shutdown(server->ssocket, SHUT_WR);
296 cifs_dbg(FYI, "Post shutdown state: 0x%x Flags: 0x%lx\n", server->ssocket->state,
297 server->ssocket->flags);
298 sock_release(server->ssocket);
299 server->ssocket = NULL;
301 server->sequence_number = 0;
302 server->session_estab = false;
303 kfree_sensitive(server->session_key.response);
304 server->session_key.response = NULL;
305 server->session_key.len = 0;
306 server->lstrp = jiffies;
308 /* mark submitted MIDs for retry and issue callback */
309 INIT_LIST_HEAD(&retry_list);
310 cifs_dbg(FYI, "%s: moving mids to private list\n", __func__);
311 spin_lock(&server->mid_lock);
312 list_for_each_entry_safe(mid, nmid, &server->pending_mid_q, qhead) {
313 kref_get(&mid->refcount);
314 if (mid->mid_state == MID_REQUEST_SUBMITTED)
315 mid->mid_state = MID_RETRY_NEEDED;
316 list_move(&mid->qhead, &retry_list);
317 mid->mid_flags |= MID_DELETED;
319 spin_unlock(&server->mid_lock);
320 cifs_server_unlock(server);
322 cifs_dbg(FYI, "%s: issuing mid callbacks\n", __func__);
323 list_for_each_entry_safe(mid, nmid, &retry_list, qhead) {
324 list_del_init(&mid->qhead);
329 if (cifs_rdma_enabled(server)) {
330 cifs_server_lock(server);
331 smbd_destroy(server);
332 cifs_server_unlock(server);
336 static bool cifs_tcp_ses_needs_reconnect(struct TCP_Server_Info *server, int num_targets)
338 spin_lock(&server->srv_lock);
339 server->nr_targets = num_targets;
340 if (server->tcpStatus == CifsExiting) {
341 /* the demux thread will exit normally next time through the loop */
342 spin_unlock(&server->srv_lock);
343 wake_up(&server->response_q);
347 cifs_dbg(FYI, "Mark tcp session as need reconnect\n");
348 trace_smb3_reconnect(server->CurrentMid, server->conn_id,
350 server->tcpStatus = CifsNeedReconnect;
352 spin_unlock(&server->srv_lock);
357 * cifs tcp session reconnection
359 * mark tcp session as reconnecting so temporarily locked
360 * mark all smb sessions as reconnecting for tcp session
361 * reconnect tcp session
362 * wake up waiters on reconnection? - (not needed currently)
364 * if mark_smb_session is passed as true, unconditionally mark
365 * the smb session (and tcon) for reconnect as well. This value
366 * doesn't really matter for non-multichannel scenario.
369 static int __cifs_reconnect(struct TCP_Server_Info *server,
370 bool mark_smb_session)
374 if (!cifs_tcp_ses_needs_reconnect(server, 1))
377 cifs_mark_tcp_ses_conns_for_reconnect(server, mark_smb_session);
379 cifs_abort_connection(server);
383 cifs_server_lock(server);
385 if (!cifs_swn_set_server_dstaddr(server)) {
386 /* resolve the hostname again to make sure that IP address is up-to-date */
387 rc = reconn_set_ipaddr_from_hostname(server);
388 cifs_dbg(FYI, "%s: reconn_set_ipaddr_from_hostname: rc=%d\n", __func__, rc);
391 if (cifs_rdma_enabled(server))
392 rc = smbd_reconnect(server);
394 rc = generic_ip_connect(server);
396 cifs_server_unlock(server);
397 cifs_dbg(FYI, "%s: reconnect error %d\n", __func__, rc);
400 atomic_inc(&tcpSesReconnectCount);
401 set_credits(server, 1);
402 spin_lock(&server->srv_lock);
403 if (server->tcpStatus != CifsExiting)
404 server->tcpStatus = CifsNeedNegotiate;
405 spin_unlock(&server->srv_lock);
406 cifs_swn_reset_server_dstaddr(server);
407 cifs_server_unlock(server);
408 mod_delayed_work(cifsiod_wq, &server->reconnect, 0);
410 } while (server->tcpStatus == CifsNeedReconnect);
412 spin_lock(&server->srv_lock);
413 if (server->tcpStatus == CifsNeedNegotiate)
414 mod_delayed_work(cifsiod_wq, &server->echo, 0);
415 spin_unlock(&server->srv_lock);
417 wake_up(&server->response_q);
421 #ifdef CONFIG_CIFS_DFS_UPCALL
422 static int __reconnect_target_unlocked(struct TCP_Server_Info *server, const char *target)
427 if (!cifs_swn_set_server_dstaddr(server)) {
428 if (server->hostname != target) {
429 hostname = extract_hostname(target);
430 if (!IS_ERR(hostname)) {
431 spin_lock(&server->srv_lock);
432 kfree(server->hostname);
433 server->hostname = hostname;
434 spin_unlock(&server->srv_lock);
436 cifs_dbg(FYI, "%s: couldn't extract hostname or address from dfs target: %ld\n",
437 __func__, PTR_ERR(hostname));
438 cifs_dbg(FYI, "%s: default to last target server: %s\n", __func__,
442 /* resolve the hostname again to make sure that IP address is up-to-date. */
443 rc = reconn_set_ipaddr_from_hostname(server);
444 cifs_dbg(FYI, "%s: reconn_set_ipaddr_from_hostname: rc=%d\n", __func__, rc);
446 /* Reconnect the socket */
447 if (cifs_rdma_enabled(server))
448 rc = smbd_reconnect(server);
450 rc = generic_ip_connect(server);
455 static int reconnect_target_unlocked(struct TCP_Server_Info *server, struct dfs_cache_tgt_list *tl,
456 struct dfs_cache_tgt_iterator **target_hint)
459 struct dfs_cache_tgt_iterator *tit;
463 /* If dfs target list is empty, then reconnect to last server */
464 tit = dfs_cache_get_tgt_iterator(tl);
466 return __reconnect_target_unlocked(server, server->hostname);
468 /* Otherwise, try every dfs target in @tl */
469 for (; tit; tit = dfs_cache_get_next_tgt(tl, tit)) {
470 rc = __reconnect_target_unlocked(server, dfs_cache_get_tgt_name(tit));
479 static int reconnect_dfs_server(struct TCP_Server_Info *server)
481 struct dfs_cache_tgt_iterator *target_hint = NULL;
482 DFS_CACHE_TGT_LIST(tl);
487 * Determine the number of dfs targets the referral path in @cifs_sb resolves to.
489 * smb2_reconnect() needs to know how long it should wait based upon the number of dfs
490 * targets (server->nr_targets). It's also possible that the cached referral was cleared
491 * through /proc/fs/cifs/dfscache or the target list is empty due to server settings after
492 * refreshing the referral, so, in this case, default it to 1.
494 mutex_lock(&server->refpath_lock);
495 if (!dfs_cache_noreq_find(server->leaf_fullpath + 1, NULL, &tl))
496 num_targets = dfs_cache_get_nr_tgts(&tl);
497 mutex_unlock(&server->refpath_lock);
501 if (!cifs_tcp_ses_needs_reconnect(server, num_targets))
505 * Unconditionally mark all sessions & tcons for reconnect as we might be connecting to a
506 * different server or share during failover. It could be improved by adding some logic to
507 * only do that in case it connects to a different server or share, though.
509 cifs_mark_tcp_ses_conns_for_reconnect(server, true);
511 cifs_abort_connection(server);
515 cifs_server_lock(server);
517 rc = reconnect_target_unlocked(server, &tl, &target_hint);
519 /* Failed to reconnect socket */
520 cifs_server_unlock(server);
521 cifs_dbg(FYI, "%s: reconnect error %d\n", __func__, rc);
526 * Socket was created. Update tcp session status to CifsNeedNegotiate so that a
527 * process waiting for reconnect will know it needs to re-establish session and tcon
528 * through the reconnected target server.
530 atomic_inc(&tcpSesReconnectCount);
531 set_credits(server, 1);
532 spin_lock(&server->srv_lock);
533 if (server->tcpStatus != CifsExiting)
534 server->tcpStatus = CifsNeedNegotiate;
535 spin_unlock(&server->srv_lock);
536 cifs_swn_reset_server_dstaddr(server);
537 cifs_server_unlock(server);
538 mod_delayed_work(cifsiod_wq, &server->reconnect, 0);
539 } while (server->tcpStatus == CifsNeedReconnect);
541 mutex_lock(&server->refpath_lock);
542 dfs_cache_noreq_update_tgthint(server->leaf_fullpath + 1, target_hint);
543 mutex_unlock(&server->refpath_lock);
544 dfs_cache_free_tgts(&tl);
546 /* Need to set up echo worker again once connection has been established */
547 spin_lock(&server->srv_lock);
548 if (server->tcpStatus == CifsNeedNegotiate)
549 mod_delayed_work(cifsiod_wq, &server->echo, 0);
550 spin_unlock(&server->srv_lock);
552 wake_up(&server->response_q);
556 int cifs_reconnect(struct TCP_Server_Info *server, bool mark_smb_session)
558 mutex_lock(&server->refpath_lock);
559 if (!server->leaf_fullpath) {
560 mutex_unlock(&server->refpath_lock);
561 return __cifs_reconnect(server, mark_smb_session);
563 mutex_unlock(&server->refpath_lock);
565 return reconnect_dfs_server(server);
568 int cifs_reconnect(struct TCP_Server_Info *server, bool mark_smb_session)
570 return __cifs_reconnect(server, mark_smb_session);
575 cifs_echo_request(struct work_struct *work)
578 struct TCP_Server_Info *server = container_of(work,
579 struct TCP_Server_Info, echo.work);
582 * We cannot send an echo if it is disabled.
583 * Also, no need to ping if we got a response recently.
586 if (server->tcpStatus == CifsNeedReconnect ||
587 server->tcpStatus == CifsExiting ||
588 server->tcpStatus == CifsNew ||
589 (server->ops->can_echo && !server->ops->can_echo(server)) ||
590 time_before(jiffies, server->lstrp + server->echo_interval - HZ))
593 rc = server->ops->echo ? server->ops->echo(server) : -ENOSYS;
594 cifs_server_dbg(FYI, "send echo request: rc = %d\n", rc);
596 /* Check witness registrations */
600 queue_delayed_work(cifsiod_wq, &server->echo, server->echo_interval);
604 allocate_buffers(struct TCP_Server_Info *server)
606 if (!server->bigbuf) {
607 server->bigbuf = (char *)cifs_buf_get();
608 if (!server->bigbuf) {
609 cifs_server_dbg(VFS, "No memory for large SMB response\n");
611 /* retry will check if exiting */
614 } else if (server->large_buf) {
615 /* we are reusing a dirty large buf, clear its start */
616 memset(server->bigbuf, 0, HEADER_SIZE(server));
619 if (!server->smallbuf) {
620 server->smallbuf = (char *)cifs_small_buf_get();
621 if (!server->smallbuf) {
622 cifs_server_dbg(VFS, "No memory for SMB response\n");
624 /* retry will check if exiting */
627 /* beginning of smb buffer is cleared in our buf_get */
629 /* if existing small buf clear beginning */
630 memset(server->smallbuf, 0, HEADER_SIZE(server));
637 server_unresponsive(struct TCP_Server_Info *server)
640 * We need to wait 3 echo intervals to make sure we handle such
642 * 1s client sends a normal SMB request
643 * 2s client gets a response
644 * 30s echo workqueue job pops, and decides we got a response recently
645 * and don't need to send another
647 * 65s kernel_recvmsg times out, and we see that we haven't gotten
648 * a response in >60s.
650 spin_lock(&server->srv_lock);
651 if ((server->tcpStatus == CifsGood ||
652 server->tcpStatus == CifsNeedNegotiate) &&
653 (!server->ops->can_echo || server->ops->can_echo(server)) &&
654 time_after(jiffies, server->lstrp + 3 * server->echo_interval)) {
655 spin_unlock(&server->srv_lock);
656 cifs_server_dbg(VFS, "has not responded in %lu seconds. Reconnecting...\n",
657 (3 * server->echo_interval) / HZ);
658 cifs_reconnect(server, false);
661 spin_unlock(&server->srv_lock);
667 zero_credits(struct TCP_Server_Info *server)
671 spin_lock(&server->req_lock);
672 val = server->credits + server->echo_credits + server->oplock_credits;
673 if (server->in_flight == 0 && val == 0) {
674 spin_unlock(&server->req_lock);
677 spin_unlock(&server->req_lock);
682 cifs_readv_from_socket(struct TCP_Server_Info *server, struct msghdr *smb_msg)
687 for (total_read = 0; msg_data_left(smb_msg); total_read += length) {
690 /* reconnect if no credits and no requests in flight */
691 if (zero_credits(server)) {
692 cifs_reconnect(server, false);
693 return -ECONNABORTED;
696 if (server_unresponsive(server))
697 return -ECONNABORTED;
698 if (cifs_rdma_enabled(server) && server->smbd_conn)
699 length = smbd_recv(server->smbd_conn, smb_msg);
701 length = sock_recvmsg(server->ssocket, smb_msg, 0);
703 spin_lock(&server->srv_lock);
704 if (server->tcpStatus == CifsExiting) {
705 spin_unlock(&server->srv_lock);
709 if (server->tcpStatus == CifsNeedReconnect) {
710 spin_unlock(&server->srv_lock);
711 cifs_reconnect(server, false);
712 return -ECONNABORTED;
714 spin_unlock(&server->srv_lock);
716 if (length == -ERESTARTSYS ||
720 * Minimum sleep to prevent looping, allowing socket
721 * to clear and app threads to set tcpStatus
722 * CifsNeedReconnect if server hung.
724 usleep_range(1000, 2000);
730 cifs_dbg(FYI, "Received no data or error: %d\n", length);
731 cifs_reconnect(server, false);
732 return -ECONNABORTED;
739 cifs_read_from_socket(struct TCP_Server_Info *server, char *buf,
740 unsigned int to_read)
742 struct msghdr smb_msg = {};
743 struct kvec iov = {.iov_base = buf, .iov_len = to_read};
744 iov_iter_kvec(&smb_msg.msg_iter, ITER_DEST, &iov, 1, to_read);
746 return cifs_readv_from_socket(server, &smb_msg);
750 cifs_discard_from_socket(struct TCP_Server_Info *server, size_t to_read)
752 struct msghdr smb_msg = {};
755 * iov_iter_discard already sets smb_msg.type and count and iov_offset
756 * and cifs_readv_from_socket sets msg_control and msg_controllen
757 * so little to initialize in struct msghdr
759 iov_iter_discard(&smb_msg.msg_iter, ITER_DEST, to_read);
761 return cifs_readv_from_socket(server, &smb_msg);
765 cifs_read_page_from_socket(struct TCP_Server_Info *server, struct page *page,
766 unsigned int page_offset, unsigned int to_read)
768 struct msghdr smb_msg = {};
771 bvec_set_page(&bv, page, to_read, page_offset);
772 iov_iter_bvec(&smb_msg.msg_iter, ITER_DEST, &bv, 1, to_read);
773 return cifs_readv_from_socket(server, &smb_msg);
777 cifs_read_iter_from_socket(struct TCP_Server_Info *server, struct iov_iter *iter,
778 unsigned int to_read)
780 struct msghdr smb_msg = { .msg_iter = *iter };
783 iov_iter_truncate(&smb_msg.msg_iter, to_read);
784 ret = cifs_readv_from_socket(server, &smb_msg);
786 iov_iter_advance(iter, ret);
791 is_smb_response(struct TCP_Server_Info *server, unsigned char type)
794 * The first byte big endian of the length field,
795 * is actually not part of the length but the type
796 * with the most common, zero, as regular data.
799 case RFC1002_SESSION_MESSAGE:
800 /* Regular SMB response */
802 case RFC1002_SESSION_KEEP_ALIVE:
803 cifs_dbg(FYI, "RFC 1002 session keep alive\n");
805 case RFC1002_POSITIVE_SESSION_RESPONSE:
806 cifs_dbg(FYI, "RFC 1002 positive session response\n");
808 case RFC1002_NEGATIVE_SESSION_RESPONSE:
810 * We get this from Windows 98 instead of an error on
811 * SMB negprot response.
813 cifs_dbg(FYI, "RFC 1002 negative session response\n");
814 /* give server a second to clean up */
817 * Always try 445 first on reconnect since we get NACK
818 * on some if we ever connected to port 139 (the NACK
819 * is since we do not begin with RFC1001 session
822 cifs_set_port((struct sockaddr *)&server->dstaddr, CIFS_PORT);
823 cifs_reconnect(server, true);
826 cifs_server_dbg(VFS, "RFC 1002 unknown response type 0x%x\n", type);
827 cifs_reconnect(server, true);
834 dequeue_mid(struct mid_q_entry *mid, bool malformed)
836 #ifdef CONFIG_CIFS_STATS2
837 mid->when_received = jiffies;
839 spin_lock(&mid->server->mid_lock);
841 mid->mid_state = MID_RESPONSE_RECEIVED;
843 mid->mid_state = MID_RESPONSE_MALFORMED;
845 * Trying to handle/dequeue a mid after the send_recv()
846 * function has finished processing it is a bug.
848 if (mid->mid_flags & MID_DELETED) {
849 spin_unlock(&mid->server->mid_lock);
850 pr_warn_once("trying to dequeue a deleted mid\n");
852 list_del_init(&mid->qhead);
853 mid->mid_flags |= MID_DELETED;
854 spin_unlock(&mid->server->mid_lock);
859 smb2_get_credits_from_hdr(char *buffer, struct TCP_Server_Info *server)
861 struct smb2_hdr *shdr = (struct smb2_hdr *)buffer;
864 * SMB1 does not use credits.
869 return le16_to_cpu(shdr->CreditRequest);
873 handle_mid(struct mid_q_entry *mid, struct TCP_Server_Info *server,
874 char *buf, int malformed)
876 if (server->ops->check_trans2 &&
877 server->ops->check_trans2(mid, server, buf, malformed))
879 mid->credits_received = smb2_get_credits_from_hdr(buf, server);
881 mid->large_buf = server->large_buf;
882 /* Was previous buf put in mpx struct for multi-rsp? */
883 if (!mid->multiRsp) {
884 /* smb buffer will be freed by user thread */
885 if (server->large_buf)
886 server->bigbuf = NULL;
888 server->smallbuf = NULL;
890 dequeue_mid(mid, malformed);
894 cifs_enable_signing(struct TCP_Server_Info *server, bool mnt_sign_required)
896 bool srv_sign_required = server->sec_mode & server->vals->signing_required;
897 bool srv_sign_enabled = server->sec_mode & server->vals->signing_enabled;
898 bool mnt_sign_enabled;
901 * Is signing required by mnt options? If not then check
902 * global_secflags to see if it is there.
904 if (!mnt_sign_required)
905 mnt_sign_required = ((global_secflags & CIFSSEC_MUST_SIGN) ==
909 * If signing is required then it's automatically enabled too,
910 * otherwise, check to see if the secflags allow it.
912 mnt_sign_enabled = mnt_sign_required ? mnt_sign_required :
913 (global_secflags & CIFSSEC_MAY_SIGN);
915 /* If server requires signing, does client allow it? */
916 if (srv_sign_required) {
917 if (!mnt_sign_enabled) {
918 cifs_dbg(VFS, "Server requires signing, but it's disabled in SecurityFlags!\n");
924 /* If client requires signing, does server allow it? */
925 if (mnt_sign_required) {
926 if (!srv_sign_enabled) {
927 cifs_dbg(VFS, "Server does not support signing!\n");
933 if (cifs_rdma_enabled(server) && server->sign)
934 cifs_dbg(VFS, "Signing is enabled, and RDMA read/write will be disabled\n");
939 static noinline_for_stack void
940 clean_demultiplex_info(struct TCP_Server_Info *server)
944 /* take it off the list, if it's not already */
945 spin_lock(&server->srv_lock);
946 list_del_init(&server->tcp_ses_list);
947 spin_unlock(&server->srv_lock);
949 cancel_delayed_work_sync(&server->echo);
951 spin_lock(&server->srv_lock);
952 server->tcpStatus = CifsExiting;
953 spin_unlock(&server->srv_lock);
954 wake_up_all(&server->response_q);
956 /* check if we have blocked requests that need to free */
957 spin_lock(&server->req_lock);
958 if (server->credits <= 0)
960 spin_unlock(&server->req_lock);
962 * Although there should not be any requests blocked on this queue it
963 * can not hurt to be paranoid and try to wake up requests that may
964 * haven been blocked when more than 50 at time were on the wire to the
965 * same server - they now will see the session is in exit state and get
966 * out of SendReceive.
968 wake_up_all(&server->request_q);
969 /* give those requests time to exit */
971 if (cifs_rdma_enabled(server))
972 smbd_destroy(server);
973 if (server->ssocket) {
974 sock_release(server->ssocket);
975 server->ssocket = NULL;
978 if (!list_empty(&server->pending_mid_q)) {
979 struct list_head dispose_list;
980 struct mid_q_entry *mid_entry;
981 struct list_head *tmp, *tmp2;
983 INIT_LIST_HEAD(&dispose_list);
984 spin_lock(&server->mid_lock);
985 list_for_each_safe(tmp, tmp2, &server->pending_mid_q) {
986 mid_entry = list_entry(tmp, struct mid_q_entry, qhead);
987 cifs_dbg(FYI, "Clearing mid %llu\n", mid_entry->mid);
988 kref_get(&mid_entry->refcount);
989 mid_entry->mid_state = MID_SHUTDOWN;
990 list_move(&mid_entry->qhead, &dispose_list);
991 mid_entry->mid_flags |= MID_DELETED;
993 spin_unlock(&server->mid_lock);
995 /* now walk dispose list and issue callbacks */
996 list_for_each_safe(tmp, tmp2, &dispose_list) {
997 mid_entry = list_entry(tmp, struct mid_q_entry, qhead);
998 cifs_dbg(FYI, "Callback mid %llu\n", mid_entry->mid);
999 list_del_init(&mid_entry->qhead);
1000 mid_entry->callback(mid_entry);
1001 release_mid(mid_entry);
1003 /* 1/8th of sec is more than enough time for them to exit */
1007 if (!list_empty(&server->pending_mid_q)) {
1009 * mpx threads have not exited yet give them at least the smb
1010 * send timeout time for long ops.
1012 * Due to delays on oplock break requests, we need to wait at
1013 * least 45 seconds before giving up on a request getting a
1014 * response and going ahead and killing cifsd.
1016 cifs_dbg(FYI, "Wait for exit from demultiplex thread\n");
1019 * If threads still have not exited they are probably never
1020 * coming home not much else we can do but free the memory.
1024 kfree(server->leaf_fullpath);
1027 length = atomic_dec_return(&tcpSesAllocCount);
1029 mempool_resize(cifs_req_poolp, length + cifs_min_rcv);
1033 standard_receive3(struct TCP_Server_Info *server, struct mid_q_entry *mid)
1036 char *buf = server->smallbuf;
1037 unsigned int pdu_length = server->pdu_size;
1039 /* make sure this will fit in a large buffer */
1040 if (pdu_length > CIFSMaxBufSize + MAX_HEADER_SIZE(server) -
1041 HEADER_PREAMBLE_SIZE(server)) {
1042 cifs_server_dbg(VFS, "SMB response too long (%u bytes)\n", pdu_length);
1043 cifs_reconnect(server, true);
1044 return -ECONNABORTED;
1047 /* switch to large buffer if too big for a small one */
1048 if (pdu_length > MAX_CIFS_SMALL_BUFFER_SIZE - 4) {
1049 server->large_buf = true;
1050 memcpy(server->bigbuf, buf, server->total_read);
1051 buf = server->bigbuf;
1054 /* now read the rest */
1055 length = cifs_read_from_socket(server, buf + HEADER_SIZE(server) - 1,
1056 pdu_length - MID_HEADER_SIZE(server));
1060 server->total_read += length;
1062 dump_smb(buf, server->total_read);
1064 return cifs_handle_standard(server, mid);
1068 cifs_handle_standard(struct TCP_Server_Info *server, struct mid_q_entry *mid)
1070 char *buf = server->large_buf ? server->bigbuf : server->smallbuf;
1074 * We know that we received enough to get to the MID as we
1075 * checked the pdu_length earlier. Now check to see
1076 * if the rest of the header is OK.
1078 * 48 bytes is enough to display the header and a little bit
1079 * into the payload for debugging purposes.
1081 rc = server->ops->check_message(buf, server->total_read, server);
1083 cifs_dump_mem("Bad SMB: ", buf,
1084 min_t(unsigned int, server->total_read, 48));
1086 if (server->ops->is_session_expired &&
1087 server->ops->is_session_expired(buf)) {
1088 cifs_reconnect(server, true);
1092 if (server->ops->is_status_pending &&
1093 server->ops->is_status_pending(buf, server))
1099 handle_mid(mid, server, buf, rc);
1104 smb2_add_credits_from_hdr(char *buffer, struct TCP_Server_Info *server)
1106 struct smb2_hdr *shdr = (struct smb2_hdr *)buffer;
1107 int scredits, in_flight;
1110 * SMB1 does not use credits.
1112 if (is_smb1(server))
1115 if (shdr->CreditRequest) {
1116 spin_lock(&server->req_lock);
1117 server->credits += le16_to_cpu(shdr->CreditRequest);
1118 scredits = server->credits;
1119 in_flight = server->in_flight;
1120 spin_unlock(&server->req_lock);
1121 wake_up(&server->request_q);
1123 trace_smb3_hdr_credits(server->CurrentMid,
1124 server->conn_id, server->hostname, scredits,
1125 le16_to_cpu(shdr->CreditRequest), in_flight);
1126 cifs_server_dbg(FYI, "%s: added %u credits total=%d\n",
1127 __func__, le16_to_cpu(shdr->CreditRequest),
1134 cifs_demultiplex_thread(void *p)
1136 int i, num_mids, length;
1137 struct TCP_Server_Info *server = p;
1138 unsigned int pdu_length;
1139 unsigned int next_offset;
1141 struct task_struct *task_to_wake = NULL;
1142 struct mid_q_entry *mids[MAX_COMPOUND];
1143 char *bufs[MAX_COMPOUND];
1144 unsigned int noreclaim_flag, num_io_timeout = 0;
1145 bool pending_reconnect = false;
1147 noreclaim_flag = memalloc_noreclaim_save();
1148 cifs_dbg(FYI, "Demultiplex PID: %d\n", task_pid_nr(current));
1150 length = atomic_inc_return(&tcpSesAllocCount);
1152 mempool_resize(cifs_req_poolp, length + cifs_min_rcv);
1155 allow_kernel_signal(SIGKILL);
1156 while (server->tcpStatus != CifsExiting) {
1157 if (try_to_freeze())
1160 if (!allocate_buffers(server))
1163 server->large_buf = false;
1164 buf = server->smallbuf;
1165 pdu_length = 4; /* enough to get RFC1001 header */
1167 length = cifs_read_from_socket(server, buf, pdu_length);
1171 if (is_smb1(server))
1172 server->total_read = length;
1174 server->total_read = 0;
1177 * The right amount was read from socket - 4 bytes,
1178 * so we can now interpret the length field.
1180 pdu_length = get_rfc1002_length(buf);
1182 cifs_dbg(FYI, "RFC1002 header 0x%x\n", pdu_length);
1183 if (!is_smb_response(server, buf[0]))
1186 pending_reconnect = false;
1188 server->pdu_size = pdu_length;
1190 /* make sure we have enough to get to the MID */
1191 if (server->pdu_size < MID_HEADER_SIZE(server)) {
1192 cifs_server_dbg(VFS, "SMB response too short (%u bytes)\n",
1194 cifs_reconnect(server, true);
1198 /* read down to the MID */
1199 length = cifs_read_from_socket(server,
1200 buf + HEADER_PREAMBLE_SIZE(server),
1201 MID_HEADER_SIZE(server));
1204 server->total_read += length;
1206 if (server->ops->next_header) {
1207 if (server->ops->next_header(server, buf, &next_offset)) {
1208 cifs_dbg(VFS, "%s: malformed response (next_offset=%u)\n",
1209 __func__, next_offset);
1210 cifs_reconnect(server, true);
1214 server->pdu_size = next_offset;
1217 memset(mids, 0, sizeof(mids));
1218 memset(bufs, 0, sizeof(bufs));
1221 if (server->ops->is_transform_hdr &&
1222 server->ops->receive_transform &&
1223 server->ops->is_transform_hdr(buf)) {
1224 length = server->ops->receive_transform(server,
1229 mids[0] = server->ops->find_mid(server, buf);
1233 if (!mids[0] || !mids[0]->receive)
1234 length = standard_receive3(server, mids[0]);
1236 length = mids[0]->receive(server, mids[0]);
1240 for (i = 0; i < num_mids; i++)
1242 release_mid(mids[i]);
1246 if (server->ops->is_status_io_timeout &&
1247 server->ops->is_status_io_timeout(buf)) {
1249 if (num_io_timeout > MAX_STATUS_IO_TIMEOUT) {
1250 cifs_server_dbg(VFS,
1251 "Number of request timeouts exceeded %d. Reconnecting",
1252 MAX_STATUS_IO_TIMEOUT);
1254 pending_reconnect = true;
1259 server->lstrp = jiffies;
1261 for (i = 0; i < num_mids; i++) {
1262 if (mids[i] != NULL) {
1263 mids[i]->resp_buf_size = server->pdu_size;
1265 if (bufs[i] != NULL) {
1266 if (server->ops->is_network_name_deleted &&
1267 server->ops->is_network_name_deleted(bufs[i],
1269 cifs_server_dbg(FYI,
1270 "Share deleted. Reconnect needed");
1274 if (!mids[i]->multiRsp || mids[i]->multiEnd)
1275 mids[i]->callback(mids[i]);
1277 release_mid(mids[i]);
1278 } else if (server->ops->is_oplock_break &&
1279 server->ops->is_oplock_break(bufs[i],
1281 smb2_add_credits_from_hdr(bufs[i], server);
1282 cifs_dbg(FYI, "Received oplock break\n");
1284 cifs_server_dbg(VFS, "No task to wake, unknown frame received! NumMids %d\n",
1285 atomic_read(&mid_count));
1286 cifs_dump_mem("Received Data is: ", bufs[i],
1287 HEADER_SIZE(server));
1288 smb2_add_credits_from_hdr(bufs[i], server);
1289 #ifdef CONFIG_CIFS_DEBUG2
1290 if (server->ops->dump_detail)
1291 server->ops->dump_detail(bufs[i],
1293 cifs_dump_mids(server);
1294 #endif /* CIFS_DEBUG2 */
1298 if (pdu_length > server->pdu_size) {
1299 if (!allocate_buffers(server))
1301 pdu_length -= server->pdu_size;
1302 server->total_read = 0;
1303 server->large_buf = false;
1304 buf = server->smallbuf;
1308 /* do this reconnect at the very end after processing all MIDs */
1309 if (pending_reconnect)
1310 cifs_reconnect(server, true);
1312 } /* end while !EXITING */
1314 /* buffer usually freed in free_mid - need to free it here on exit */
1315 cifs_buf_release(server->bigbuf);
1316 if (server->smallbuf) /* no sense logging a debug message if NULL */
1317 cifs_small_buf_release(server->smallbuf);
1319 task_to_wake = xchg(&server->tsk, NULL);
1320 clean_demultiplex_info(server);
1322 /* if server->tsk was NULL then wait for a signal before exiting */
1323 if (!task_to_wake) {
1324 set_current_state(TASK_INTERRUPTIBLE);
1325 while (!signal_pending(current)) {
1327 set_current_state(TASK_INTERRUPTIBLE);
1329 set_current_state(TASK_RUNNING);
1332 memalloc_noreclaim_restore(noreclaim_flag);
1333 module_put_and_kthread_exit(0);
1337 cifs_ipaddr_cmp(struct sockaddr *srcaddr, struct sockaddr *rhs)
1339 struct sockaddr_in *saddr4 = (struct sockaddr_in *)srcaddr;
1340 struct sockaddr_in *vaddr4 = (struct sockaddr_in *)rhs;
1341 struct sockaddr_in6 *saddr6 = (struct sockaddr_in6 *)srcaddr;
1342 struct sockaddr_in6 *vaddr6 = (struct sockaddr_in6 *)rhs;
1344 switch (srcaddr->sa_family) {
1346 switch (rhs->sa_family) {
1356 switch (rhs->sa_family) {
1360 return memcmp(saddr4, vaddr4,
1361 sizeof(struct sockaddr_in));
1369 switch (rhs->sa_family) {
1374 return memcmp(saddr6,
1376 sizeof(struct sockaddr_in6));
1382 return -1; /* don't expect to be here */
1387 * Returns true if srcaddr isn't specified and rhs isn't specified, or
1388 * if srcaddr is specified and matches the IP address of the rhs argument
1391 cifs_match_ipaddr(struct sockaddr *srcaddr, struct sockaddr *rhs)
1393 switch (srcaddr->sa_family) {
1395 return (rhs->sa_family == AF_UNSPEC);
1397 struct sockaddr_in *saddr4 = (struct sockaddr_in *)srcaddr;
1398 struct sockaddr_in *vaddr4 = (struct sockaddr_in *)rhs;
1399 return (saddr4->sin_addr.s_addr == vaddr4->sin_addr.s_addr);
1402 struct sockaddr_in6 *saddr6 = (struct sockaddr_in6 *)srcaddr;
1403 struct sockaddr_in6 *vaddr6 = (struct sockaddr_in6 *)rhs;
1404 return (ipv6_addr_equal(&saddr6->sin6_addr, &vaddr6->sin6_addr)
1405 && saddr6->sin6_scope_id == vaddr6->sin6_scope_id);
1409 return false; /* don't expect to be here */
1414 * If no port is specified in addr structure, we try to match with 445 port
1415 * and if it fails - with 139 ports. It should be called only if address
1416 * families of server and addr are equal.
1419 match_port(struct TCP_Server_Info *server, struct sockaddr *addr)
1421 __be16 port, *sport;
1423 /* SMBDirect manages its own ports, don't match it here */
1427 switch (addr->sa_family) {
1429 sport = &((struct sockaddr_in *) &server->dstaddr)->sin_port;
1430 port = ((struct sockaddr_in *) addr)->sin_port;
1433 sport = &((struct sockaddr_in6 *) &server->dstaddr)->sin6_port;
1434 port = ((struct sockaddr_in6 *) addr)->sin6_port;
1442 port = htons(CIFS_PORT);
1446 port = htons(RFC1001_PORT);
1449 return port == *sport;
1452 static bool match_server_address(struct TCP_Server_Info *server, struct sockaddr *addr)
1454 if (!cifs_match_ipaddr(addr, (struct sockaddr *)&server->dstaddr))
1461 match_security(struct TCP_Server_Info *server, struct smb3_fs_context *ctx)
1464 * The select_sectype function should either return the ctx->sectype
1465 * that was specified, or "Unspecified" if that sectype was not
1466 * compatible with the given NEGOTIATE request.
1468 if (server->ops->select_sectype(server, ctx->sectype)
1473 * Now check if signing mode is acceptable. No need to check
1474 * global_secflags at this point since if MUST_SIGN is set then
1475 * the server->sign had better be too.
1477 if (ctx->sign && !server->sign)
1483 /* this function must be called with srv_lock held */
1484 static int match_server(struct TCP_Server_Info *server,
1485 struct smb3_fs_context *ctx,
1488 struct sockaddr *addr = (struct sockaddr *)&ctx->dstaddr;
1490 lockdep_assert_held(&server->srv_lock);
1492 if (ctx->nosharesock)
1495 /* this server does not share socket */
1496 if (server->nosharesock)
1499 /* If multidialect negotiation see if existing sessions match one */
1500 if (strcmp(ctx->vals->version_string, SMB3ANY_VERSION_STRING) == 0) {
1501 if (server->vals->protocol_id < SMB30_PROT_ID)
1503 } else if (strcmp(ctx->vals->version_string,
1504 SMBDEFAULT_VERSION_STRING) == 0) {
1505 if (server->vals->protocol_id < SMB21_PROT_ID)
1507 } else if ((server->vals != ctx->vals) || (server->ops != ctx->ops))
1510 if (!net_eq(cifs_net_ns(server), current->nsproxy->net_ns))
1513 if (!cifs_match_ipaddr((struct sockaddr *)&ctx->srcaddr,
1514 (struct sockaddr *)&server->srcaddr))
1517 * When matching cifs.ko superblocks (@match_super == true), we can't
1518 * really match either @server->leaf_fullpath or @server->dstaddr
1519 * directly since this @server might belong to a completely different
1520 * server -- in case of domain-based DFS referrals or DFS links -- as
1521 * provided earlier by mount(2) through 'source' and 'ip' options.
1523 * Otherwise, match the DFS referral in @server->leaf_fullpath or the
1524 * destination address in @server->dstaddr.
1526 * When using 'nodfs' mount option, we avoid sharing it with DFS
1527 * connections as they might failover.
1531 if (server->leaf_fullpath) {
1532 if (!ctx->leaf_fullpath ||
1533 strcasecmp(server->leaf_fullpath,
1534 ctx->leaf_fullpath))
1536 } else if (ctx->leaf_fullpath) {
1539 } else if (server->leaf_fullpath) {
1545 * Match for a regular connection (address/hostname/port) which has no
1546 * DFS referrals set.
1548 if (!server->leaf_fullpath &&
1549 (strcasecmp(server->hostname, ctx->server_hostname) ||
1550 !match_server_address(server, addr) ||
1551 !match_port(server, addr)))
1554 if (!match_security(server, ctx))
1557 if (server->echo_interval != ctx->echo_interval * HZ)
1560 if (server->rdma != ctx->rdma)
1563 if (server->ignore_signature != ctx->ignore_signature)
1566 if (server->min_offload != ctx->min_offload)
1572 struct TCP_Server_Info *
1573 cifs_find_tcp_session(struct smb3_fs_context *ctx)
1575 struct TCP_Server_Info *server;
1577 spin_lock(&cifs_tcp_ses_lock);
1578 list_for_each_entry(server, &cifs_tcp_ses_list, tcp_ses_list) {
1579 spin_lock(&server->srv_lock);
1581 * Skip ses channels since they're only handled in lower layers
1582 * (e.g. cifs_send_recv).
1584 if (SERVER_IS_CHAN(server) ||
1585 !match_server(server, ctx, false)) {
1586 spin_unlock(&server->srv_lock);
1589 spin_unlock(&server->srv_lock);
1591 ++server->srv_count;
1592 spin_unlock(&cifs_tcp_ses_lock);
1593 cifs_dbg(FYI, "Existing tcp session with server found\n");
1596 spin_unlock(&cifs_tcp_ses_lock);
1601 cifs_put_tcp_session(struct TCP_Server_Info *server, int from_reconnect)
1603 struct task_struct *task;
1605 spin_lock(&cifs_tcp_ses_lock);
1606 if (--server->srv_count > 0) {
1607 spin_unlock(&cifs_tcp_ses_lock);
1611 /* srv_count can never go negative */
1612 WARN_ON(server->srv_count < 0);
1614 put_net(cifs_net_ns(server));
1616 list_del_init(&server->tcp_ses_list);
1617 spin_unlock(&cifs_tcp_ses_lock);
1619 cancel_delayed_work_sync(&server->echo);
1623 * Avoid deadlock here: reconnect work calls
1624 * cifs_put_tcp_session() at its end. Need to be sure
1625 * that reconnect work does nothing with server pointer after
1628 cancel_delayed_work(&server->reconnect);
1630 cancel_delayed_work_sync(&server->reconnect);
1632 /* For secondary channels, we pick up ref-count on the primary server */
1633 if (SERVER_IS_CHAN(server))
1634 cifs_put_tcp_session(server->primary_server, from_reconnect);
1636 spin_lock(&server->srv_lock);
1637 server->tcpStatus = CifsExiting;
1638 spin_unlock(&server->srv_lock);
1640 cifs_crypto_secmech_release(server);
1642 kfree_sensitive(server->session_key.response);
1643 server->session_key.response = NULL;
1644 server->session_key.len = 0;
1645 kfree(server->hostname);
1646 server->hostname = NULL;
1648 task = xchg(&server->tsk, NULL);
1650 send_sig(SIGKILL, task, 1);
1653 struct TCP_Server_Info *
1654 cifs_get_tcp_session(struct smb3_fs_context *ctx,
1655 struct TCP_Server_Info *primary_server)
1657 struct TCP_Server_Info *tcp_ses = NULL;
1660 cifs_dbg(FYI, "UNC: %s\n", ctx->UNC);
1662 /* see if we already have a matching tcp_ses */
1663 tcp_ses = cifs_find_tcp_session(ctx);
1667 tcp_ses = kzalloc(sizeof(struct TCP_Server_Info), GFP_KERNEL);
1673 tcp_ses->hostname = kstrdup(ctx->server_hostname, GFP_KERNEL);
1674 if (!tcp_ses->hostname) {
1679 if (ctx->leaf_fullpath) {
1680 tcp_ses->leaf_fullpath = kstrdup(ctx->leaf_fullpath, GFP_KERNEL);
1681 if (!tcp_ses->leaf_fullpath) {
1687 if (ctx->nosharesock)
1688 tcp_ses->nosharesock = true;
1690 tcp_ses->ops = ctx->ops;
1691 tcp_ses->vals = ctx->vals;
1692 cifs_set_net_ns(tcp_ses, get_net(current->nsproxy->net_ns));
1694 tcp_ses->conn_id = atomic_inc_return(&tcpSesNextId);
1695 tcp_ses->noblockcnt = ctx->rootfs;
1696 tcp_ses->noblocksnd = ctx->noblocksnd || ctx->rootfs;
1697 tcp_ses->noautotune = ctx->noautotune;
1698 tcp_ses->tcp_nodelay = ctx->sockopt_tcp_nodelay;
1699 tcp_ses->rdma = ctx->rdma;
1700 tcp_ses->in_flight = 0;
1701 tcp_ses->max_in_flight = 0;
1702 tcp_ses->credits = 1;
1703 if (primary_server) {
1704 spin_lock(&cifs_tcp_ses_lock);
1705 ++primary_server->srv_count;
1706 spin_unlock(&cifs_tcp_ses_lock);
1707 tcp_ses->primary_server = primary_server;
1709 init_waitqueue_head(&tcp_ses->response_q);
1710 init_waitqueue_head(&tcp_ses->request_q);
1711 INIT_LIST_HEAD(&tcp_ses->pending_mid_q);
1712 mutex_init(&tcp_ses->_srv_mutex);
1713 memcpy(tcp_ses->workstation_RFC1001_name,
1714 ctx->source_rfc1001_name, RFC1001_NAME_LEN_WITH_NULL);
1715 memcpy(tcp_ses->server_RFC1001_name,
1716 ctx->target_rfc1001_name, RFC1001_NAME_LEN_WITH_NULL);
1717 tcp_ses->session_estab = false;
1718 tcp_ses->sequence_number = 0;
1719 tcp_ses->channel_sequence_num = 0; /* only tracked for primary channel */
1720 tcp_ses->reconnect_instance = 1;
1721 tcp_ses->lstrp = jiffies;
1722 tcp_ses->compress_algorithm = cpu_to_le16(ctx->compression);
1723 spin_lock_init(&tcp_ses->req_lock);
1724 spin_lock_init(&tcp_ses->srv_lock);
1725 spin_lock_init(&tcp_ses->mid_lock);
1726 INIT_LIST_HEAD(&tcp_ses->tcp_ses_list);
1727 INIT_LIST_HEAD(&tcp_ses->smb_ses_list);
1728 INIT_DELAYED_WORK(&tcp_ses->echo, cifs_echo_request);
1729 INIT_DELAYED_WORK(&tcp_ses->reconnect, smb2_reconnect_server);
1730 mutex_init(&tcp_ses->reconnect_mutex);
1731 #ifdef CONFIG_CIFS_DFS_UPCALL
1732 mutex_init(&tcp_ses->refpath_lock);
1734 memcpy(&tcp_ses->srcaddr, &ctx->srcaddr,
1735 sizeof(tcp_ses->srcaddr));
1736 memcpy(&tcp_ses->dstaddr, &ctx->dstaddr,
1737 sizeof(tcp_ses->dstaddr));
1738 if (ctx->use_client_guid)
1739 memcpy(tcp_ses->client_guid, ctx->client_guid,
1740 SMB2_CLIENT_GUID_SIZE);
1742 generate_random_uuid(tcp_ses->client_guid);
1744 * at this point we are the only ones with the pointer
1745 * to the struct since the kernel thread not created yet
1746 * no need to spinlock this init of tcpStatus or srv_count
1748 tcp_ses->tcpStatus = CifsNew;
1749 ++tcp_ses->srv_count;
1751 if (ctx->echo_interval >= SMB_ECHO_INTERVAL_MIN &&
1752 ctx->echo_interval <= SMB_ECHO_INTERVAL_MAX)
1753 tcp_ses->echo_interval = ctx->echo_interval * HZ;
1755 tcp_ses->echo_interval = SMB_ECHO_INTERVAL_DEFAULT * HZ;
1756 if (tcp_ses->rdma) {
1757 #ifndef CONFIG_CIFS_SMB_DIRECT
1758 cifs_dbg(VFS, "CONFIG_CIFS_SMB_DIRECT is not enabled\n");
1760 goto out_err_crypto_release;
1762 tcp_ses->smbd_conn = smbd_get_connection(
1763 tcp_ses, (struct sockaddr *)&ctx->dstaddr);
1764 if (tcp_ses->smbd_conn) {
1765 cifs_dbg(VFS, "RDMA transport established\n");
1767 goto smbd_connected;
1770 goto out_err_crypto_release;
1773 rc = ip_connect(tcp_ses);
1775 cifs_dbg(VFS, "Error connecting to socket. Aborting operation.\n");
1776 goto out_err_crypto_release;
1780 * since we're in a cifs function already, we know that
1781 * this will succeed. No need for try_module_get().
1783 __module_get(THIS_MODULE);
1784 tcp_ses->tsk = kthread_run(cifs_demultiplex_thread,
1786 if (IS_ERR(tcp_ses->tsk)) {
1787 rc = PTR_ERR(tcp_ses->tsk);
1788 cifs_dbg(VFS, "error %d create cifsd thread\n", rc);
1789 module_put(THIS_MODULE);
1790 goto out_err_crypto_release;
1792 tcp_ses->min_offload = ctx->min_offload;
1794 * at this point we are the only ones with the pointer
1795 * to the struct since the kernel thread not created yet
1796 * no need to spinlock this update of tcpStatus
1798 spin_lock(&tcp_ses->srv_lock);
1799 tcp_ses->tcpStatus = CifsNeedNegotiate;
1800 spin_unlock(&tcp_ses->srv_lock);
1802 if ((ctx->max_credits < 20) || (ctx->max_credits > 60000))
1803 tcp_ses->max_credits = SMB2_MAX_CREDITS_AVAILABLE;
1805 tcp_ses->max_credits = ctx->max_credits;
1807 tcp_ses->nr_targets = 1;
1808 tcp_ses->ignore_signature = ctx->ignore_signature;
1809 /* thread spawned, put it on the list */
1810 spin_lock(&cifs_tcp_ses_lock);
1811 list_add(&tcp_ses->tcp_ses_list, &cifs_tcp_ses_list);
1812 spin_unlock(&cifs_tcp_ses_lock);
1814 /* queue echo request delayed work */
1815 queue_delayed_work(cifsiod_wq, &tcp_ses->echo, tcp_ses->echo_interval);
1819 out_err_crypto_release:
1820 cifs_crypto_secmech_release(tcp_ses);
1822 put_net(cifs_net_ns(tcp_ses));
1826 if (SERVER_IS_CHAN(tcp_ses))
1827 cifs_put_tcp_session(tcp_ses->primary_server, false);
1828 kfree(tcp_ses->hostname);
1829 kfree(tcp_ses->leaf_fullpath);
1830 if (tcp_ses->ssocket)
1831 sock_release(tcp_ses->ssocket);
1837 /* this function must be called with ses_lock and chan_lock held */
1838 static int match_session(struct cifs_ses *ses, struct smb3_fs_context *ctx)
1840 if (ctx->sectype != Unspecified &&
1841 ctx->sectype != ses->sectype)
1845 * If an existing session is limited to less channels than
1846 * requested, it should not be reused
1848 if (ses->chan_max < ctx->max_channels)
1851 switch (ses->sectype) {
1853 if (!uid_eq(ctx->cred_uid, ses->cred_uid))
1857 /* NULL username means anonymous session */
1858 if (ses->user_name == NULL) {
1864 /* anything else takes username/password */
1865 if (strncmp(ses->user_name,
1866 ctx->username ? ctx->username : "",
1867 CIFS_MAX_USERNAME_LEN))
1869 if ((ctx->username && strlen(ctx->username) != 0) &&
1870 ses->password != NULL &&
1871 strncmp(ses->password,
1872 ctx->password ? ctx->password : "",
1873 CIFS_MAX_PASSWORD_LEN))
1877 if (strcmp(ctx->local_nls->charset, ses->local_nls->charset))
1884 * cifs_setup_ipc - helper to setup the IPC tcon for the session
1885 * @ses: smb session to issue the request on
1886 * @ctx: the superblock configuration context to use for building the
1887 * new tree connection for the IPC (interprocess communication RPC)
1889 * A new IPC connection is made and stored in the session
1890 * tcon_ipc. The IPC tcon has the same lifetime as the session.
1893 cifs_setup_ipc(struct cifs_ses *ses, struct smb3_fs_context *ctx)
1896 struct cifs_tcon *tcon;
1897 char unc[SERVER_NAME_LENGTH + sizeof("//x/IPC$")] = {0};
1899 struct TCP_Server_Info *server = ses->server;
1902 * If the mount request that resulted in the creation of the
1903 * session requires encryption, force IPC to be encrypted too.
1906 if (server->capabilities & SMB2_GLOBAL_CAP_ENCRYPTION)
1909 cifs_server_dbg(VFS,
1910 "IPC: server doesn't support encryption\n");
1915 /* no need to setup directory caching on IPC share, so pass in false */
1916 tcon = tcon_info_alloc(false);
1920 spin_lock(&server->srv_lock);
1921 scnprintf(unc, sizeof(unc), "\\\\%s\\IPC$", server->hostname);
1922 spin_unlock(&server->srv_lock);
1928 rc = server->ops->tree_connect(xid, ses, unc, tcon, ctx->local_nls);
1932 cifs_server_dbg(VFS, "failed to connect to IPC (rc=%d)\n", rc);
1937 cifs_dbg(FYI, "IPC tcon rc=%d ipc tid=0x%x\n", rc, tcon->tid);
1939 spin_lock(&tcon->tc_lock);
1940 tcon->status = TID_GOOD;
1941 spin_unlock(&tcon->tc_lock);
1942 ses->tcon_ipc = tcon;
1948 * cifs_free_ipc - helper to release the session IPC tcon
1949 * @ses: smb session to unmount the IPC from
1951 * Needs to be called everytime a session is destroyed.
1953 * On session close, the IPC is closed and the server must release all tcons of the session.
1954 * No need to send a tree disconnect here.
1956 * Besides, it will make the server to not close durable and resilient files on session close, as
1957 * specified in MS-SMB2 3.3.5.6 Receiving an SMB2 LOGOFF Request.
1960 cifs_free_ipc(struct cifs_ses *ses)
1962 struct cifs_tcon *tcon = ses->tcon_ipc;
1968 ses->tcon_ipc = NULL;
1972 static struct cifs_ses *
1973 cifs_find_smb_ses(struct TCP_Server_Info *server, struct smb3_fs_context *ctx)
1975 struct cifs_ses *ses, *ret = NULL;
1977 spin_lock(&cifs_tcp_ses_lock);
1978 list_for_each_entry(ses, &server->smb_ses_list, smb_ses_list) {
1979 spin_lock(&ses->ses_lock);
1980 if (ses->ses_status == SES_EXITING) {
1981 spin_unlock(&ses->ses_lock);
1984 spin_lock(&ses->chan_lock);
1985 if (match_session(ses, ctx)) {
1986 spin_unlock(&ses->chan_lock);
1987 spin_unlock(&ses->ses_lock);
1991 spin_unlock(&ses->chan_lock);
1992 spin_unlock(&ses->ses_lock);
1995 cifs_smb_ses_inc_refcount(ret);
1996 spin_unlock(&cifs_tcp_ses_lock);
2000 void __cifs_put_smb_ses(struct cifs_ses *ses)
2002 unsigned int rc, xid;
2003 unsigned int chan_count;
2004 struct TCP_Server_Info *server = ses->server;
2006 spin_lock(&ses->ses_lock);
2007 if (ses->ses_status == SES_EXITING) {
2008 spin_unlock(&ses->ses_lock);
2011 spin_unlock(&ses->ses_lock);
2013 cifs_dbg(FYI, "%s: ses_count=%d\n", __func__, ses->ses_count);
2015 "%s: ses ipc: %s\n", __func__, ses->tcon_ipc ? ses->tcon_ipc->tree_name : "NONE");
2017 spin_lock(&cifs_tcp_ses_lock);
2018 if (--ses->ses_count > 0) {
2019 spin_unlock(&cifs_tcp_ses_lock);
2022 spin_lock(&ses->ses_lock);
2023 if (ses->ses_status == SES_GOOD)
2024 ses->ses_status = SES_EXITING;
2025 spin_unlock(&ses->ses_lock);
2026 spin_unlock(&cifs_tcp_ses_lock);
2028 /* ses_count can never go negative */
2029 WARN_ON(ses->ses_count < 0);
2031 spin_lock(&ses->ses_lock);
2032 if (ses->ses_status == SES_EXITING && server->ops->logoff) {
2033 spin_unlock(&ses->ses_lock);
2036 rc = server->ops->logoff(xid, ses);
2038 cifs_server_dbg(VFS, "%s: Session Logoff failure rc=%d\n",
2042 spin_unlock(&ses->ses_lock);
2046 spin_lock(&cifs_tcp_ses_lock);
2047 list_del_init(&ses->smb_ses_list);
2048 spin_unlock(&cifs_tcp_ses_lock);
2050 chan_count = ses->chan_count;
2052 /* close any extra channels */
2053 if (chan_count > 1) {
2056 for (i = 1; i < chan_count; i++) {
2057 if (ses->chans[i].iface) {
2058 kref_put(&ses->chans[i].iface->refcount, release_iface);
2059 ses->chans[i].iface = NULL;
2061 cifs_put_tcp_session(ses->chans[i].server, 0);
2062 ses->chans[i].server = NULL;
2066 /* we now account for primary channel in iface->refcount */
2067 if (ses->chans[0].iface) {
2068 kref_put(&ses->chans[0].iface->refcount, release_iface);
2069 ses->chans[0].server = NULL;
2073 cifs_put_tcp_session(server, 0);
2078 /* strlen("cifs:a:") + CIFS_MAX_DOMAINNAME_LEN + 1 */
2079 #define CIFSCREDS_DESC_SIZE (7 + CIFS_MAX_DOMAINNAME_LEN + 1)
2081 /* Populate username and pw fields from keyring if possible */
2083 cifs_set_cifscreds(struct smb3_fs_context *ctx, struct cifs_ses *ses)
2087 const char *delim, *payload;
2091 struct TCP_Server_Info *server = ses->server;
2092 struct sockaddr_in *sa;
2093 struct sockaddr_in6 *sa6;
2094 const struct user_key_payload *upayload;
2096 desc = kmalloc(CIFSCREDS_DESC_SIZE, GFP_KERNEL);
2100 /* try to find an address key first */
2101 switch (server->dstaddr.ss_family) {
2103 sa = (struct sockaddr_in *)&server->dstaddr;
2104 sprintf(desc, "cifs:a:%pI4", &sa->sin_addr.s_addr);
2107 sa6 = (struct sockaddr_in6 *)&server->dstaddr;
2108 sprintf(desc, "cifs:a:%pI6c", &sa6->sin6_addr.s6_addr);
2111 cifs_dbg(FYI, "Bad ss_family (%hu)\n",
2112 server->dstaddr.ss_family);
2117 cifs_dbg(FYI, "%s: desc=%s\n", __func__, desc);
2118 key = request_key(&key_type_logon, desc, "");
2120 if (!ses->domainName) {
2121 cifs_dbg(FYI, "domainName is NULL\n");
2126 /* didn't work, try to find a domain key */
2127 sprintf(desc, "cifs:d:%s", ses->domainName);
2128 cifs_dbg(FYI, "%s: desc=%s\n", __func__, desc);
2129 key = request_key(&key_type_logon, desc, "");
2137 down_read(&key->sem);
2138 upayload = user_key_payload_locked(key);
2139 if (IS_ERR_OR_NULL(upayload)) {
2140 rc = upayload ? PTR_ERR(upayload) : -EINVAL;
2144 /* find first : in payload */
2145 payload = upayload->data;
2146 delim = strnchr(payload, upayload->datalen, ':');
2147 cifs_dbg(FYI, "payload=%s\n", payload);
2149 cifs_dbg(FYI, "Unable to find ':' in payload (datalen=%d)\n",
2155 len = delim - payload;
2156 if (len > CIFS_MAX_USERNAME_LEN || len <= 0) {
2157 cifs_dbg(FYI, "Bad value from username search (len=%zd)\n",
2163 ctx->username = kstrndup(payload, len, GFP_KERNEL);
2164 if (!ctx->username) {
2165 cifs_dbg(FYI, "Unable to allocate %zd bytes for username\n",
2170 cifs_dbg(FYI, "%s: username=%s\n", __func__, ctx->username);
2172 len = key->datalen - (len + 1);
2173 if (len > CIFS_MAX_PASSWORD_LEN || len <= 0) {
2174 cifs_dbg(FYI, "Bad len for password search (len=%zd)\n", len);
2176 kfree(ctx->username);
2177 ctx->username = NULL;
2182 ctx->password = kstrndup(delim, len, GFP_KERNEL);
2183 if (!ctx->password) {
2184 cifs_dbg(FYI, "Unable to allocate %zd bytes for password\n",
2187 kfree(ctx->username);
2188 ctx->username = NULL;
2193 * If we have a domain key then we must set the domainName in the
2196 if (is_domain && ses->domainName) {
2197 ctx->domainname = kstrdup(ses->domainName, GFP_KERNEL);
2198 if (!ctx->domainname) {
2199 cifs_dbg(FYI, "Unable to allocate %zd bytes for domain\n",
2202 kfree(ctx->username);
2203 ctx->username = NULL;
2204 kfree_sensitive(ctx->password);
2205 ctx->password = NULL;
2210 strscpy(ctx->workstation_name, ses->workstation_name, sizeof(ctx->workstation_name));
2217 cifs_dbg(FYI, "%s: returning %d\n", __func__, rc);
2220 #else /* ! CONFIG_KEYS */
2222 cifs_set_cifscreds(struct smb3_fs_context *ctx __attribute__((unused)),
2223 struct cifs_ses *ses __attribute__((unused)))
2227 #endif /* CONFIG_KEYS */
2230 * cifs_get_smb_ses - get a session matching @ctx data from @server
2231 * @server: server to setup the session to
2232 * @ctx: superblock configuration context to use to setup the session
2234 * This function assumes it is being called from cifs_mount() where we
2235 * already got a server reference (server refcount +1). See
2236 * cifs_get_tcon() for refcount explanations.
2239 cifs_get_smb_ses(struct TCP_Server_Info *server, struct smb3_fs_context *ctx)
2243 struct cifs_ses *ses;
2244 struct sockaddr_in *addr = (struct sockaddr_in *)&server->dstaddr;
2245 struct sockaddr_in6 *addr6 = (struct sockaddr_in6 *)&server->dstaddr;
2249 ses = cifs_find_smb_ses(server, ctx);
2251 cifs_dbg(FYI, "Existing smb sess found (status=%d)\n",
2254 spin_lock(&ses->chan_lock);
2255 if (cifs_chan_needs_reconnect(ses, server)) {
2256 spin_unlock(&ses->chan_lock);
2257 cifs_dbg(FYI, "Session needs reconnect\n");
2259 mutex_lock(&ses->session_mutex);
2260 rc = cifs_negotiate_protocol(xid, ses, server);
2262 mutex_unlock(&ses->session_mutex);
2263 /* problem -- put our ses reference */
2264 cifs_put_smb_ses(ses);
2269 rc = cifs_setup_session(xid, ses, server,
2272 mutex_unlock(&ses->session_mutex);
2273 /* problem -- put our reference */
2274 cifs_put_smb_ses(ses);
2278 mutex_unlock(&ses->session_mutex);
2280 spin_lock(&ses->chan_lock);
2282 spin_unlock(&ses->chan_lock);
2284 /* existing SMB ses has a server reference already */
2285 cifs_put_tcp_session(server, 0);
2292 cifs_dbg(FYI, "Existing smb sess not found\n");
2293 ses = sesInfoAlloc();
2297 /* new SMB session uses our server ref */
2298 ses->server = server;
2299 if (server->dstaddr.ss_family == AF_INET6)
2300 sprintf(ses->ip_addr, "%pI6", &addr6->sin6_addr);
2302 sprintf(ses->ip_addr, "%pI4", &addr->sin_addr);
2304 if (ctx->username) {
2305 ses->user_name = kstrdup(ctx->username, GFP_KERNEL);
2306 if (!ses->user_name)
2310 /* ctx->password freed at unmount */
2311 if (ctx->password) {
2312 ses->password = kstrdup(ctx->password, GFP_KERNEL);
2316 if (ctx->domainname) {
2317 ses->domainName = kstrdup(ctx->domainname, GFP_KERNEL);
2318 if (!ses->domainName)
2322 strscpy(ses->workstation_name, ctx->workstation_name, sizeof(ses->workstation_name));
2324 if (ctx->domainauto)
2325 ses->domainAuto = ctx->domainauto;
2326 ses->cred_uid = ctx->cred_uid;
2327 ses->linux_uid = ctx->linux_uid;
2329 ses->sectype = ctx->sectype;
2330 ses->sign = ctx->sign;
2331 ses->local_nls = load_nls(ctx->local_nls->charset);
2333 /* add server as first channel */
2334 spin_lock(&ses->chan_lock);
2335 ses->chans[0].server = server;
2336 ses->chan_count = 1;
2337 ses->chan_max = ctx->multichannel ? ctx->max_channels:1;
2338 ses->chans_need_reconnect = 1;
2339 spin_unlock(&ses->chan_lock);
2341 mutex_lock(&ses->session_mutex);
2342 rc = cifs_negotiate_protocol(xid, ses, server);
2344 rc = cifs_setup_session(xid, ses, server, ctx->local_nls);
2345 mutex_unlock(&ses->session_mutex);
2347 /* each channel uses a different signing key */
2348 spin_lock(&ses->chan_lock);
2349 memcpy(ses->chans[0].signkey, ses->smb3signingkey,
2350 sizeof(ses->smb3signingkey));
2351 spin_unlock(&ses->chan_lock);
2357 * success, put it on the list and add it as first channel
2358 * note: the session becomes active soon after this. So you'll
2359 * need to lock before changing something in the session.
2361 spin_lock(&cifs_tcp_ses_lock);
2362 ses->dfs_root_ses = ctx->dfs_root_ses;
2363 if (ses->dfs_root_ses)
2364 ses->dfs_root_ses->ses_count++;
2365 list_add(&ses->smb_ses_list, &server->smb_ses_list);
2366 spin_unlock(&cifs_tcp_ses_lock);
2368 cifs_setup_ipc(ses, ctx);
2380 /* this function must be called with tc_lock held */
2381 static int match_tcon(struct cifs_tcon *tcon, struct smb3_fs_context *ctx)
2383 struct TCP_Server_Info *server = tcon->ses->server;
2385 if (tcon->status == TID_EXITING)
2388 if (tcon->origin_fullpath) {
2390 !dfs_src_pathname_equal(ctx->source,
2391 tcon->origin_fullpath))
2393 } else if (!server->leaf_fullpath &&
2394 strncmp(tcon->tree_name, ctx->UNC, MAX_TREE_SIZE)) {
2397 if (tcon->seal != ctx->seal)
2399 if (tcon->snapshot_time != ctx->snapshot_time)
2401 if (tcon->handle_timeout != ctx->handle_timeout)
2403 if (tcon->no_lease != ctx->no_lease)
2405 if (tcon->nodelete != ctx->nodelete)
2410 static struct cifs_tcon *
2411 cifs_find_tcon(struct cifs_ses *ses, struct smb3_fs_context *ctx)
2413 struct cifs_tcon *tcon;
2415 spin_lock(&cifs_tcp_ses_lock);
2416 list_for_each_entry(tcon, &ses->tcon_list, tcon_list) {
2417 spin_lock(&tcon->tc_lock);
2418 if (!match_tcon(tcon, ctx)) {
2419 spin_unlock(&tcon->tc_lock);
2423 spin_unlock(&tcon->tc_lock);
2424 spin_unlock(&cifs_tcp_ses_lock);
2427 spin_unlock(&cifs_tcp_ses_lock);
2432 cifs_put_tcon(struct cifs_tcon *tcon)
2435 struct cifs_ses *ses;
2438 * IPC tcon share the lifetime of their session and are
2439 * destroyed in the session put function
2441 if (tcon == NULL || tcon->ipc)
2445 cifs_dbg(FYI, "%s: tc_count=%d\n", __func__, tcon->tc_count);
2446 spin_lock(&cifs_tcp_ses_lock);
2447 spin_lock(&tcon->tc_lock);
2448 if (--tcon->tc_count > 0) {
2449 spin_unlock(&tcon->tc_lock);
2450 spin_unlock(&cifs_tcp_ses_lock);
2454 /* tc_count can never go negative */
2455 WARN_ON(tcon->tc_count < 0);
2457 list_del_init(&tcon->tcon_list);
2458 tcon->status = TID_EXITING;
2459 spin_unlock(&tcon->tc_lock);
2460 spin_unlock(&cifs_tcp_ses_lock);
2462 /* cancel polling of interfaces */
2463 cancel_delayed_work_sync(&tcon->query_interfaces);
2464 #ifdef CONFIG_CIFS_DFS_UPCALL
2465 cancel_delayed_work_sync(&tcon->dfs_cache_work);
2468 if (tcon->use_witness) {
2471 rc = cifs_swn_unregister(tcon);
2473 cifs_dbg(VFS, "%s: Failed to unregister for witness notifications: %d\n",
2479 if (ses->server->ops->tree_disconnect)
2480 ses->server->ops->tree_disconnect(xid, tcon);
2483 cifs_fscache_release_super_cookie(tcon);
2485 cifs_put_smb_ses(ses);
2489 * cifs_get_tcon - get a tcon matching @ctx data from @ses
2490 * @ses: smb session to issue the request on
2491 * @ctx: the superblock configuration context to use for building the
2493 * - tcon refcount is the number of mount points using the tcon.
2494 * - ses refcount is the number of tcon using the session.
2496 * 1. This function assumes it is being called from cifs_mount() where
2497 * we already got a session reference (ses refcount +1).
2499 * 2. Since we're in the context of adding a mount point, the end
2500 * result should be either:
2502 * a) a new tcon already allocated with refcount=1 (1 mount point) and
2503 * its session refcount incremented (1 new tcon). This +1 was
2504 * already done in (1).
2506 * b) an existing tcon with refcount+1 (add a mount point to it) and
2507 * identical ses refcount (no new tcon). Because of (1) we need to
2508 * decrement the ses refcount.
2510 static struct cifs_tcon *
2511 cifs_get_tcon(struct cifs_ses *ses, struct smb3_fs_context *ctx)
2513 struct cifs_tcon *tcon;
2517 tcon = cifs_find_tcon(ses, ctx);
2520 * tcon has refcount already incremented but we need to
2521 * decrement extra ses reference gotten by caller (case b)
2523 cifs_dbg(FYI, "Found match on UNC path\n");
2524 cifs_put_smb_ses(ses);
2528 if (!ses->server->ops->tree_connect) {
2533 if (ses->server->dialect >= SMB20_PROT_ID &&
2534 (ses->server->capabilities & SMB2_GLOBAL_CAP_DIRECTORY_LEASING))
2535 nohandlecache = ctx->nohandlecache;
2537 nohandlecache = true;
2538 tcon = tcon_info_alloc(!nohandlecache);
2543 tcon->nohandlecache = nohandlecache;
2545 if (ctx->snapshot_time) {
2546 if (ses->server->vals->protocol_id == 0) {
2548 "Use SMB2 or later for snapshot mount option\n");
2552 tcon->snapshot_time = ctx->snapshot_time;
2555 if (ctx->handle_timeout) {
2556 if (ses->server->vals->protocol_id == 0) {
2558 "Use SMB2.1 or later for handle timeout option\n");
2562 tcon->handle_timeout = ctx->handle_timeout;
2566 if (ctx->password) {
2567 tcon->password = kstrdup(ctx->password, GFP_KERNEL);
2568 if (!tcon->password) {
2575 if (ses->server->vals->protocol_id == 0) {
2577 "SMB3 or later required for encryption\n");
2580 } else if (tcon->ses->server->capabilities &
2581 SMB2_GLOBAL_CAP_ENCRYPTION)
2584 cifs_dbg(VFS, "Encryption is not supported on share\n");
2590 if (ctx->linux_ext) {
2591 if (ses->server->posix_ext_supported) {
2592 tcon->posix_extensions = true;
2593 pr_warn_once("SMB3.11 POSIX Extensions are experimental\n");
2594 } else if ((ses->server->vals->protocol_id == SMB311_PROT_ID) ||
2595 (strcmp(ses->server->vals->version_string,
2596 SMB3ANY_VERSION_STRING) == 0) ||
2597 (strcmp(ses->server->vals->version_string,
2598 SMBDEFAULT_VERSION_STRING) == 0)) {
2599 cifs_dbg(VFS, "Server does not support mounting with posix SMB3.11 extensions\n");
2603 cifs_dbg(VFS, "Check vers= mount option. SMB3.11 "
2604 "disabled but required for POSIX extensions\n");
2611 rc = ses->server->ops->tree_connect(xid, ses, ctx->UNC, tcon,
2614 cifs_dbg(FYI, "Tcon rc = %d\n", rc);
2618 tcon->use_persistent = false;
2619 /* check if SMB2 or later, CIFS does not support persistent handles */
2620 if (ctx->persistent) {
2621 if (ses->server->vals->protocol_id == 0) {
2623 "SMB3 or later required for persistent handles\n");
2626 } else if (ses->server->capabilities &
2627 SMB2_GLOBAL_CAP_PERSISTENT_HANDLES)
2628 tcon->use_persistent = true;
2629 else /* persistent handles requested but not supported */ {
2631 "Persistent handles not supported on share\n");
2635 } else if ((tcon->capabilities & SMB2_SHARE_CAP_CONTINUOUS_AVAILABILITY)
2636 && (ses->server->capabilities & SMB2_GLOBAL_CAP_PERSISTENT_HANDLES)
2637 && (ctx->nopersistent == false)) {
2638 cifs_dbg(FYI, "enabling persistent handles\n");
2639 tcon->use_persistent = true;
2640 } else if (ctx->resilient) {
2641 if (ses->server->vals->protocol_id == 0) {
2643 "SMB2.1 or later required for resilient handles\n");
2647 tcon->use_resilient = true;
2650 tcon->use_witness = false;
2651 if (IS_ENABLED(CONFIG_CIFS_SWN_UPCALL) && ctx->witness) {
2652 if (ses->server->vals->protocol_id >= SMB30_PROT_ID) {
2653 if (tcon->capabilities & SMB2_SHARE_CAP_CLUSTER) {
2655 * Set witness in use flag in first place
2656 * to retry registration in the echo task
2658 tcon->use_witness = true;
2659 /* And try to register immediately */
2660 rc = cifs_swn_register(tcon);
2662 cifs_dbg(VFS, "Failed to register for witness notifications: %d\n", rc);
2666 /* TODO: try to extend for non-cluster uses (eg multichannel) */
2667 cifs_dbg(VFS, "witness requested on mount but no CLUSTER capability on share\n");
2672 cifs_dbg(VFS, "SMB3 or later required for witness option\n");
2678 /* If the user really knows what they are doing they can override */
2679 if (tcon->share_flags & SMB2_SHAREFLAG_NO_CACHING) {
2681 cifs_dbg(VFS, "cache=ro requested on mount but NO_CACHING flag set on share\n");
2682 else if (ctx->cache_rw)
2683 cifs_dbg(VFS, "cache=singleclient requested on mount but NO_CACHING flag set on share\n");
2686 if (ctx->no_lease) {
2687 if (ses->server->vals->protocol_id == 0) {
2689 "SMB2 or later required for nolease option\n");
2693 tcon->no_lease = ctx->no_lease;
2697 * We can have only one retry value for a connection to a share so for
2698 * resources mounted more than once to the same server share the last
2699 * value passed in for the retry flag is used.
2701 tcon->retry = ctx->retry;
2702 tcon->nocase = ctx->nocase;
2703 tcon->broken_sparse_sup = ctx->no_sparse;
2704 tcon->max_cached_dirs = ctx->max_cached_dirs;
2705 tcon->nodelete = ctx->nodelete;
2706 tcon->local_lease = ctx->local_lease;
2707 INIT_LIST_HEAD(&tcon->pending_opens);
2708 tcon->status = TID_GOOD;
2710 INIT_DELAYED_WORK(&tcon->query_interfaces,
2711 smb2_query_server_interfaces);
2712 if (ses->server->dialect >= SMB30_PROT_ID &&
2713 (ses->server->capabilities & SMB2_GLOBAL_CAP_MULTI_CHANNEL)) {
2714 /* schedule query interfaces poll */
2715 queue_delayed_work(cifsiod_wq, &tcon->query_interfaces,
2716 (SMB_INTERFACE_POLL_INTERVAL * HZ));
2718 #ifdef CONFIG_CIFS_DFS_UPCALL
2719 INIT_DELAYED_WORK(&tcon->dfs_cache_work, dfs_cache_refresh);
2721 spin_lock(&cifs_tcp_ses_lock);
2722 list_add(&tcon->tcon_list, &ses->tcon_list);
2723 spin_unlock(&cifs_tcp_ses_lock);
2733 cifs_put_tlink(struct tcon_link *tlink)
2735 if (!tlink || IS_ERR(tlink))
2738 if (!atomic_dec_and_test(&tlink->tl_count) ||
2739 test_bit(TCON_LINK_IN_TREE, &tlink->tl_flags)) {
2740 tlink->tl_time = jiffies;
2744 if (!IS_ERR(tlink_tcon(tlink)))
2745 cifs_put_tcon(tlink_tcon(tlink));
2751 compare_mount_options(struct super_block *sb, struct cifs_mnt_data *mnt_data)
2753 struct cifs_sb_info *old = CIFS_SB(sb);
2754 struct cifs_sb_info *new = mnt_data->cifs_sb;
2755 unsigned int oldflags = old->mnt_cifs_flags & CIFS_MOUNT_MASK;
2756 unsigned int newflags = new->mnt_cifs_flags & CIFS_MOUNT_MASK;
2758 if ((sb->s_flags & CIFS_MS_MASK) != (mnt_data->flags & CIFS_MS_MASK))
2761 if (old->mnt_cifs_serverino_autodisabled)
2762 newflags &= ~CIFS_MOUNT_SERVER_INUM;
2764 if (oldflags != newflags)
2768 * We want to share sb only if we don't specify an r/wsize or
2769 * specified r/wsize is greater than or equal to existing one.
2771 if (new->ctx->wsize && new->ctx->wsize < old->ctx->wsize)
2774 if (new->ctx->rsize && new->ctx->rsize < old->ctx->rsize)
2777 if (!uid_eq(old->ctx->linux_uid, new->ctx->linux_uid) ||
2778 !gid_eq(old->ctx->linux_gid, new->ctx->linux_gid))
2781 if (old->ctx->file_mode != new->ctx->file_mode ||
2782 old->ctx->dir_mode != new->ctx->dir_mode)
2785 if (strcmp(old->local_nls->charset, new->local_nls->charset))
2788 if (old->ctx->acregmax != new->ctx->acregmax)
2790 if (old->ctx->acdirmax != new->ctx->acdirmax)
2792 if (old->ctx->closetimeo != new->ctx->closetimeo)
2798 static int match_prepath(struct super_block *sb,
2799 struct cifs_tcon *tcon,
2800 struct cifs_mnt_data *mnt_data)
2802 struct smb3_fs_context *ctx = mnt_data->ctx;
2803 struct cifs_sb_info *old = CIFS_SB(sb);
2804 struct cifs_sb_info *new = mnt_data->cifs_sb;
2805 bool old_set = (old->mnt_cifs_flags & CIFS_MOUNT_USE_PREFIX_PATH) &&
2807 bool new_set = (new->mnt_cifs_flags & CIFS_MOUNT_USE_PREFIX_PATH) &&
2810 if (tcon->origin_fullpath &&
2811 dfs_src_pathname_equal(tcon->origin_fullpath, ctx->source))
2814 if (old_set && new_set && !strcmp(new->prepath, old->prepath))
2816 else if (!old_set && !new_set)
2823 cifs_match_super(struct super_block *sb, void *data)
2825 struct cifs_mnt_data *mnt_data = data;
2826 struct smb3_fs_context *ctx;
2827 struct cifs_sb_info *cifs_sb;
2828 struct TCP_Server_Info *tcp_srv;
2829 struct cifs_ses *ses;
2830 struct cifs_tcon *tcon;
2831 struct tcon_link *tlink;
2834 spin_lock(&cifs_tcp_ses_lock);
2835 cifs_sb = CIFS_SB(sb);
2837 /* We do not want to use a superblock that has been shutdown */
2838 if (CIFS_MOUNT_SHUTDOWN & cifs_sb->mnt_cifs_flags) {
2839 spin_unlock(&cifs_tcp_ses_lock);
2843 tlink = cifs_get_tlink(cifs_sb_master_tlink(cifs_sb));
2844 if (IS_ERR_OR_NULL(tlink)) {
2845 pr_warn_once("%s: skip super matching due to bad tlink(%p)\n",
2847 spin_unlock(&cifs_tcp_ses_lock);
2850 tcon = tlink_tcon(tlink);
2852 tcp_srv = ses->server;
2854 ctx = mnt_data->ctx;
2856 spin_lock(&tcp_srv->srv_lock);
2857 spin_lock(&ses->ses_lock);
2858 spin_lock(&ses->chan_lock);
2859 spin_lock(&tcon->tc_lock);
2860 if (!match_server(tcp_srv, ctx, true) ||
2861 !match_session(ses, ctx) ||
2862 !match_tcon(tcon, ctx) ||
2863 !match_prepath(sb, tcon, mnt_data)) {
2868 rc = compare_mount_options(sb, mnt_data);
2870 spin_unlock(&tcon->tc_lock);
2871 spin_unlock(&ses->chan_lock);
2872 spin_unlock(&ses->ses_lock);
2873 spin_unlock(&tcp_srv->srv_lock);
2875 spin_unlock(&cifs_tcp_ses_lock);
2876 cifs_put_tlink(tlink);
2880 #ifdef CONFIG_DEBUG_LOCK_ALLOC
2881 static struct lock_class_key cifs_key[2];
2882 static struct lock_class_key cifs_slock_key[2];
2885 cifs_reclassify_socket4(struct socket *sock)
2887 struct sock *sk = sock->sk;
2888 BUG_ON(!sock_allow_reclassification(sk));
2889 sock_lock_init_class_and_name(sk, "slock-AF_INET-CIFS",
2890 &cifs_slock_key[0], "sk_lock-AF_INET-CIFS", &cifs_key[0]);
2894 cifs_reclassify_socket6(struct socket *sock)
2896 struct sock *sk = sock->sk;
2897 BUG_ON(!sock_allow_reclassification(sk));
2898 sock_lock_init_class_and_name(sk, "slock-AF_INET6-CIFS",
2899 &cifs_slock_key[1], "sk_lock-AF_INET6-CIFS", &cifs_key[1]);
2903 cifs_reclassify_socket4(struct socket *sock)
2908 cifs_reclassify_socket6(struct socket *sock)
2913 /* See RFC1001 section 14 on representation of Netbios names */
2914 static void rfc1002mangle(char *target, char *source, unsigned int length)
2918 for (i = 0, j = 0; i < (length); i++) {
2919 /* mask a nibble at a time and encode */
2920 target[j] = 'A' + (0x0F & (source[i] >> 4));
2921 target[j+1] = 'A' + (0x0F & source[i]);
2928 bind_socket(struct TCP_Server_Info *server)
2931 if (server->srcaddr.ss_family != AF_UNSPEC) {
2932 /* Bind to the specified local IP address */
2933 struct socket *socket = server->ssocket;
2934 rc = kernel_bind(socket,
2935 (struct sockaddr *) &server->srcaddr,
2936 sizeof(server->srcaddr));
2938 struct sockaddr_in *saddr4;
2939 struct sockaddr_in6 *saddr6;
2940 saddr4 = (struct sockaddr_in *)&server->srcaddr;
2941 saddr6 = (struct sockaddr_in6 *)&server->srcaddr;
2942 if (saddr6->sin6_family == AF_INET6)
2943 cifs_server_dbg(VFS, "Failed to bind to: %pI6c, error: %d\n",
2944 &saddr6->sin6_addr, rc);
2946 cifs_server_dbg(VFS, "Failed to bind to: %pI4, error: %d\n",
2947 &saddr4->sin_addr.s_addr, rc);
2954 ip_rfc1001_connect(struct TCP_Server_Info *server)
2958 * some servers require RFC1001 sessinit before sending
2959 * negprot - BB check reconnection in case where second
2960 * sessinit is sent but no second negprot
2962 struct rfc1002_session_packet req = {};
2963 struct smb_hdr *smb_buf = (struct smb_hdr *)&req;
2966 req.trailer.session_req.called_len = sizeof(req.trailer.session_req.called_name);
2968 if (server->server_RFC1001_name[0] != 0)
2969 rfc1002mangle(req.trailer.session_req.called_name,
2970 server->server_RFC1001_name,
2971 RFC1001_NAME_LEN_WITH_NULL);
2973 rfc1002mangle(req.trailer.session_req.called_name,
2974 DEFAULT_CIFS_CALLED_NAME,
2975 RFC1001_NAME_LEN_WITH_NULL);
2977 req.trailer.session_req.calling_len = sizeof(req.trailer.session_req.calling_name);
2979 /* calling name ends in null (byte 16) from old smb convention */
2980 if (server->workstation_RFC1001_name[0] != 0)
2981 rfc1002mangle(req.trailer.session_req.calling_name,
2982 server->workstation_RFC1001_name,
2983 RFC1001_NAME_LEN_WITH_NULL);
2985 rfc1002mangle(req.trailer.session_req.calling_name,
2987 RFC1001_NAME_LEN_WITH_NULL);
2990 * As per rfc1002, @len must be the number of bytes that follows the
2991 * length field of a rfc1002 session request payload.
2993 len = sizeof(req) - offsetof(struct rfc1002_session_packet, trailer.session_req);
2995 smb_buf->smb_buf_length = cpu_to_be32((RFC1002_SESSION_REQUEST << 24) | len);
2996 rc = smb_send(server, smb_buf, len);
2998 * RFC1001 layer in at least one server requires very short break before
2999 * negprot presumably because not expecting negprot to follow so fast.
3000 * This is a simple solution that works without complicating the code
3001 * and causes no significant slowing down on mount for everyone else
3003 usleep_range(1000, 2000);
3009 generic_ip_connect(struct TCP_Server_Info *server)
3011 struct sockaddr *saddr;
3012 struct socket *socket;
3017 saddr = (struct sockaddr *) &server->dstaddr;
3019 if (server->dstaddr.ss_family == AF_INET6) {
3020 struct sockaddr_in6 *ipv6 = (struct sockaddr_in6 *)&server->dstaddr;
3022 sport = ipv6->sin6_port;
3023 slen = sizeof(struct sockaddr_in6);
3025 cifs_dbg(FYI, "%s: connecting to [%pI6]:%d\n", __func__, &ipv6->sin6_addr,
3028 struct sockaddr_in *ipv4 = (struct sockaddr_in *)&server->dstaddr;
3030 sport = ipv4->sin_port;
3031 slen = sizeof(struct sockaddr_in);
3033 cifs_dbg(FYI, "%s: connecting to %pI4:%d\n", __func__, &ipv4->sin_addr,
3037 if (server->ssocket) {
3038 socket = server->ssocket;
3040 rc = __sock_create(cifs_net_ns(server), sfamily, SOCK_STREAM,
3041 IPPROTO_TCP, &server->ssocket, 1);
3043 cifs_server_dbg(VFS, "Error %d creating socket\n", rc);
3047 /* BB other socket options to set KEEPALIVE, NODELAY? */
3048 cifs_dbg(FYI, "Socket created\n");
3049 socket = server->ssocket;
3050 socket->sk->sk_allocation = GFP_NOFS;
3051 socket->sk->sk_use_task_frag = false;
3052 if (sfamily == AF_INET6)
3053 cifs_reclassify_socket6(socket);
3055 cifs_reclassify_socket4(socket);
3058 rc = bind_socket(server);
3063 * Eventually check for other socket options to change from
3064 * the default. sock_setsockopt not used because it expects
3067 socket->sk->sk_rcvtimeo = 7 * HZ;
3068 socket->sk->sk_sndtimeo = 5 * HZ;
3070 /* make the bufsizes depend on wsize/rsize and max requests */
3071 if (server->noautotune) {
3072 if (socket->sk->sk_sndbuf < (200 * 1024))
3073 socket->sk->sk_sndbuf = 200 * 1024;
3074 if (socket->sk->sk_rcvbuf < (140 * 1024))
3075 socket->sk->sk_rcvbuf = 140 * 1024;
3078 if (server->tcp_nodelay)
3079 tcp_sock_set_nodelay(socket->sk);
3081 cifs_dbg(FYI, "sndbuf %d rcvbuf %d rcvtimeo 0x%lx\n",
3082 socket->sk->sk_sndbuf,
3083 socket->sk->sk_rcvbuf, socket->sk->sk_rcvtimeo);
3085 rc = kernel_connect(socket, saddr, slen,
3086 server->noblockcnt ? O_NONBLOCK : 0);
3088 * When mounting SMB root file systems, we do not want to block in
3089 * connect. Otherwise bail out and then let cifs_reconnect() perform
3090 * reconnect failover - if possible.
3092 if (server->noblockcnt && rc == -EINPROGRESS)
3095 cifs_dbg(FYI, "Error %d connecting to server\n", rc);
3096 trace_smb3_connect_err(server->hostname, server->conn_id, &server->dstaddr, rc);
3097 sock_release(socket);
3098 server->ssocket = NULL;
3101 trace_smb3_connect_done(server->hostname, server->conn_id, &server->dstaddr);
3102 if (sport == htons(RFC1001_PORT))
3103 rc = ip_rfc1001_connect(server);
3109 ip_connect(struct TCP_Server_Info *server)
3112 struct sockaddr_in6 *addr6 = (struct sockaddr_in6 *)&server->dstaddr;
3113 struct sockaddr_in *addr = (struct sockaddr_in *)&server->dstaddr;
3115 if (server->dstaddr.ss_family == AF_INET6)
3116 sport = &addr6->sin6_port;
3118 sport = &addr->sin_port;
3123 /* try with 445 port at first */
3124 *sport = htons(CIFS_PORT);
3126 rc = generic_ip_connect(server);
3130 /* if it failed, try with 139 port */
3131 *sport = htons(RFC1001_PORT);
3134 return generic_ip_connect(server);
3137 #ifdef CONFIG_CIFS_ALLOW_INSECURE_LEGACY
3138 void reset_cifs_unix_caps(unsigned int xid, struct cifs_tcon *tcon,
3139 struct cifs_sb_info *cifs_sb, struct smb3_fs_context *ctx)
3142 * If we are reconnecting then should we check to see if
3143 * any requested capabilities changed locally e.g. via
3144 * remount but we can not do much about it here
3145 * if they have (even if we could detect it by the following)
3146 * Perhaps we could add a backpointer to array of sb from tcon
3147 * or if we change to make all sb to same share the same
3148 * sb as NFS - then we only have one backpointer to sb.
3149 * What if we wanted to mount the server share twice once with
3150 * and once without posixacls or posix paths?
3152 __u64 saved_cap = le64_to_cpu(tcon->fsUnixInfo.Capability);
3154 if (ctx && ctx->no_linux_ext) {
3155 tcon->fsUnixInfo.Capability = 0;
3156 tcon->unix_ext = 0; /* Unix Extensions disabled */
3157 cifs_dbg(FYI, "Linux protocol extensions disabled\n");
3160 tcon->unix_ext = 1; /* Unix Extensions supported */
3162 if (!tcon->unix_ext) {
3163 cifs_dbg(FYI, "Unix extensions disabled so not set on reconnect\n");
3167 if (!CIFSSMBQFSUnixInfo(xid, tcon)) {
3168 __u64 cap = le64_to_cpu(tcon->fsUnixInfo.Capability);
3169 cifs_dbg(FYI, "unix caps which server supports %lld\n", cap);
3171 * check for reconnect case in which we do not
3172 * want to change the mount behavior if we can avoid it
3176 * turn off POSIX ACL and PATHNAMES if not set
3177 * originally at mount time
3179 if ((saved_cap & CIFS_UNIX_POSIX_ACL_CAP) == 0)
3180 cap &= ~CIFS_UNIX_POSIX_ACL_CAP;
3181 if ((saved_cap & CIFS_UNIX_POSIX_PATHNAMES_CAP) == 0) {
3182 if (cap & CIFS_UNIX_POSIX_PATHNAMES_CAP)
3183 cifs_dbg(VFS, "POSIXPATH support change\n");
3184 cap &= ~CIFS_UNIX_POSIX_PATHNAMES_CAP;
3185 } else if ((cap & CIFS_UNIX_POSIX_PATHNAMES_CAP) == 0) {
3186 cifs_dbg(VFS, "possible reconnect error\n");
3187 cifs_dbg(VFS, "server disabled POSIX path support\n");
3191 if (cap & CIFS_UNIX_TRANSPORT_ENCRYPTION_MANDATORY_CAP)
3192 cifs_dbg(VFS, "per-share encryption not supported yet\n");
3194 cap &= CIFS_UNIX_CAP_MASK;
3195 if (ctx && ctx->no_psx_acl)
3196 cap &= ~CIFS_UNIX_POSIX_ACL_CAP;
3197 else if (CIFS_UNIX_POSIX_ACL_CAP & cap) {
3198 cifs_dbg(FYI, "negotiated posix acl support\n");
3200 cifs_sb->mnt_cifs_flags |=
3201 CIFS_MOUNT_POSIXACL;
3204 if (ctx && ctx->posix_paths == 0)
3205 cap &= ~CIFS_UNIX_POSIX_PATHNAMES_CAP;
3206 else if (cap & CIFS_UNIX_POSIX_PATHNAMES_CAP) {
3207 cifs_dbg(FYI, "negotiate posix pathnames\n");
3209 cifs_sb->mnt_cifs_flags |=
3210 CIFS_MOUNT_POSIX_PATHS;
3213 cifs_dbg(FYI, "Negotiate caps 0x%x\n", (int)cap);
3214 #ifdef CONFIG_CIFS_DEBUG2
3215 if (cap & CIFS_UNIX_FCNTL_CAP)
3216 cifs_dbg(FYI, "FCNTL cap\n");
3217 if (cap & CIFS_UNIX_EXTATTR_CAP)
3218 cifs_dbg(FYI, "EXTATTR cap\n");
3219 if (cap & CIFS_UNIX_POSIX_PATHNAMES_CAP)
3220 cifs_dbg(FYI, "POSIX path cap\n");
3221 if (cap & CIFS_UNIX_XATTR_CAP)
3222 cifs_dbg(FYI, "XATTR cap\n");
3223 if (cap & CIFS_UNIX_POSIX_ACL_CAP)
3224 cifs_dbg(FYI, "POSIX ACL cap\n");
3225 if (cap & CIFS_UNIX_LARGE_READ_CAP)
3226 cifs_dbg(FYI, "very large read cap\n");
3227 if (cap & CIFS_UNIX_LARGE_WRITE_CAP)
3228 cifs_dbg(FYI, "very large write cap\n");
3229 if (cap & CIFS_UNIX_TRANSPORT_ENCRYPTION_CAP)
3230 cifs_dbg(FYI, "transport encryption cap\n");
3231 if (cap & CIFS_UNIX_TRANSPORT_ENCRYPTION_MANDATORY_CAP)
3232 cifs_dbg(FYI, "mandatory transport encryption cap\n");
3233 #endif /* CIFS_DEBUG2 */
3234 if (CIFSSMBSetFSUnixInfo(xid, tcon, cap)) {
3236 cifs_dbg(FYI, "resetting capabilities failed\n");
3238 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");
3243 #endif /* CONFIG_CIFS_ALLOW_INSECURE_LEGACY */
3245 int cifs_setup_cifs_sb(struct cifs_sb_info *cifs_sb)
3247 struct smb3_fs_context *ctx = cifs_sb->ctx;
3249 INIT_DELAYED_WORK(&cifs_sb->prune_tlinks, cifs_prune_tlinks);
3251 spin_lock_init(&cifs_sb->tlink_tree_lock);
3252 cifs_sb->tlink_tree = RB_ROOT;
3254 cifs_dbg(FYI, "file mode: %04ho dir mode: %04ho\n",
3255 ctx->file_mode, ctx->dir_mode);
3257 /* this is needed for ASCII cp to Unicode converts */
3258 if (ctx->iocharset == NULL) {
3259 /* load_nls_default cannot return null */
3260 cifs_sb->local_nls = load_nls_default();
3262 cifs_sb->local_nls = load_nls(ctx->iocharset);
3263 if (cifs_sb->local_nls == NULL) {
3264 cifs_dbg(VFS, "CIFS mount error: iocharset %s not found\n",
3269 ctx->local_nls = cifs_sb->local_nls;
3271 smb3_update_mnt_flags(cifs_sb);
3274 cifs_dbg(FYI, "mounting share using direct i/o\n");
3275 if (ctx->cache_ro) {
3276 cifs_dbg(VFS, "mounting share with read only caching. Ensure that the share will not be modified while in use.\n");
3277 cifs_sb->mnt_cifs_flags |= CIFS_MOUNT_RO_CACHE;
3278 } else if (ctx->cache_rw) {
3279 cifs_dbg(VFS, "mounting share in single client RW caching mode. Ensure that no other systems will be accessing the share.\n");
3280 cifs_sb->mnt_cifs_flags |= (CIFS_MOUNT_RO_CACHE |
3281 CIFS_MOUNT_RW_CACHE);
3284 if ((ctx->cifs_acl) && (ctx->dynperm))
3285 cifs_dbg(VFS, "mount option dynperm ignored if cifsacl mount option supported\n");
3288 cifs_sb->prepath = kstrdup(ctx->prepath, GFP_KERNEL);
3289 if (cifs_sb->prepath == NULL)
3291 cifs_sb->mnt_cifs_flags |= CIFS_MOUNT_USE_PREFIX_PATH;
3297 /* Release all succeed connections */
3298 void cifs_mount_put_conns(struct cifs_mount_ctx *mnt_ctx)
3303 cifs_put_tcon(mnt_ctx->tcon);
3304 else if (mnt_ctx->ses)
3305 cifs_put_smb_ses(mnt_ctx->ses);
3306 else if (mnt_ctx->server)
3307 cifs_put_tcp_session(mnt_ctx->server, 0);
3308 mnt_ctx->cifs_sb->mnt_cifs_flags &= ~CIFS_MOUNT_POSIX_PATHS;
3309 free_xid(mnt_ctx->xid);
3312 int cifs_mount_get_session(struct cifs_mount_ctx *mnt_ctx)
3314 struct TCP_Server_Info *server = NULL;
3315 struct smb3_fs_context *ctx;
3316 struct cifs_ses *ses = NULL;
3322 if (WARN_ON_ONCE(!mnt_ctx || !mnt_ctx->fs_ctx)) {
3326 ctx = mnt_ctx->fs_ctx;
3328 /* get a reference to a tcp session */
3329 server = cifs_get_tcp_session(ctx, NULL);
3330 if (IS_ERR(server)) {
3331 rc = PTR_ERR(server);
3336 /* get a reference to a SMB session */
3337 ses = cifs_get_smb_ses(server, ctx);
3344 if ((ctx->persistent == true) && (!(ses->server->capabilities &
3345 SMB2_GLOBAL_CAP_PERSISTENT_HANDLES))) {
3346 cifs_server_dbg(VFS, "persistent handles not supported by server\n");
3352 mnt_ctx->server = server;
3354 mnt_ctx->tcon = NULL;
3359 int cifs_mount_get_tcon(struct cifs_mount_ctx *mnt_ctx)
3361 struct TCP_Server_Info *server;
3362 struct cifs_sb_info *cifs_sb;
3363 struct smb3_fs_context *ctx;
3364 struct cifs_tcon *tcon = NULL;
3367 if (WARN_ON_ONCE(!mnt_ctx || !mnt_ctx->server || !mnt_ctx->ses || !mnt_ctx->fs_ctx ||
3368 !mnt_ctx->cifs_sb)) {
3372 server = mnt_ctx->server;
3373 ctx = mnt_ctx->fs_ctx;
3374 cifs_sb = mnt_ctx->cifs_sb;
3376 /* search for existing tcon to this server share */
3377 tcon = cifs_get_tcon(mnt_ctx->ses, ctx);
3384 /* if new SMB3.11 POSIX extensions are supported do not remap / and \ */
3385 if (tcon->posix_extensions)
3386 cifs_sb->mnt_cifs_flags |= CIFS_MOUNT_POSIX_PATHS;
3388 #ifdef CONFIG_CIFS_ALLOW_INSECURE_LEGACY
3389 /* tell server which Unix caps we support */
3390 if (cap_unix(tcon->ses)) {
3392 * reset of caps checks mount to see if unix extensions disabled
3393 * for just this mount.
3395 reset_cifs_unix_caps(mnt_ctx->xid, tcon, cifs_sb, ctx);
3396 spin_lock(&tcon->ses->server->srv_lock);
3397 if ((tcon->ses->server->tcpStatus == CifsNeedReconnect) &&
3398 (le64_to_cpu(tcon->fsUnixInfo.Capability) &
3399 CIFS_UNIX_TRANSPORT_ENCRYPTION_MANDATORY_CAP)) {
3400 spin_unlock(&tcon->ses->server->srv_lock);
3404 spin_unlock(&tcon->ses->server->srv_lock);
3406 #endif /* CONFIG_CIFS_ALLOW_INSECURE_LEGACY */
3407 tcon->unix_ext = 0; /* server does not support them */
3409 /* do not care if a following call succeed - informational */
3410 if (!tcon->pipe && server->ops->qfs_tcon) {
3411 server->ops->qfs_tcon(mnt_ctx->xid, tcon, cifs_sb);
3412 if (cifs_sb->mnt_cifs_flags & CIFS_MOUNT_RO_CACHE) {
3413 if (tcon->fsDevInfo.DeviceCharacteristics &
3414 cpu_to_le32(FILE_READ_ONLY_DEVICE))
3415 cifs_dbg(VFS, "mounted to read only share\n");
3416 else if ((cifs_sb->mnt_cifs_flags &
3417 CIFS_MOUNT_RW_CACHE) == 0)
3418 cifs_dbg(VFS, "read only mount of RW share\n");
3419 /* no need to log a RW mount of a typical RW share */
3424 * Clamp the rsize/wsize mount arguments if they are too big for the server
3425 * and set the rsize/wsize to the negotiated values if not passed in by
3428 if ((cifs_sb->ctx->wsize == 0) ||
3429 (cifs_sb->ctx->wsize > server->ops->negotiate_wsize(tcon, ctx)))
3430 cifs_sb->ctx->wsize = server->ops->negotiate_wsize(tcon, ctx);
3431 if ((cifs_sb->ctx->rsize == 0) ||
3432 (cifs_sb->ctx->rsize > server->ops->negotiate_rsize(tcon, ctx)))
3433 cifs_sb->ctx->rsize = server->ops->negotiate_rsize(tcon, ctx);
3436 * The cookie is initialized from volume info returned above.
3437 * Inside cifs_fscache_get_super_cookie it checks
3438 * that we do not get super cookie twice.
3440 if (cifs_sb->mnt_cifs_flags & CIFS_MOUNT_FSCACHE)
3441 cifs_fscache_get_super_cookie(tcon);
3444 mnt_ctx->tcon = tcon;
3448 static int mount_setup_tlink(struct cifs_sb_info *cifs_sb, struct cifs_ses *ses,
3449 struct cifs_tcon *tcon)
3451 struct tcon_link *tlink;
3453 /* hang the tcon off of the superblock */
3454 tlink = kzalloc(sizeof(*tlink), GFP_KERNEL);
3458 tlink->tl_uid = ses->linux_uid;
3459 tlink->tl_tcon = tcon;
3460 tlink->tl_time = jiffies;
3461 set_bit(TCON_LINK_MASTER, &tlink->tl_flags);
3462 set_bit(TCON_LINK_IN_TREE, &tlink->tl_flags);
3464 cifs_sb->master_tlink = tlink;
3465 spin_lock(&cifs_sb->tlink_tree_lock);
3466 tlink_rb_insert(&cifs_sb->tlink_tree, tlink);
3467 spin_unlock(&cifs_sb->tlink_tree_lock);
3469 queue_delayed_work(cifsiod_wq, &cifs_sb->prune_tlinks,
3475 cifs_are_all_path_components_accessible(struct TCP_Server_Info *server,
3477 struct cifs_tcon *tcon,
3478 struct cifs_sb_info *cifs_sb,
3485 int skip = added_treename ? 1 : 0;
3487 sep = CIFS_DIR_SEP(cifs_sb);
3490 rc = server->ops->is_path_accessible(xid, tcon, cifs_sb, "");
3492 /* skip separators */
3497 /* next separator */
3498 while (*s && *s != sep)
3501 * if the treename is added, we then have to skip the first
3502 * part within the separators
3509 * temporarily null-terminate the path at the end of
3510 * the current component
3514 rc = server->ops->is_path_accessible(xid, tcon, cifs_sb,
3522 * Check if path is remote (i.e. a DFS share).
3524 * Return -EREMOTE if it is, otherwise 0 or -errno.
3526 int cifs_is_path_remote(struct cifs_mount_ctx *mnt_ctx)
3529 struct cifs_sb_info *cifs_sb = mnt_ctx->cifs_sb;
3530 struct TCP_Server_Info *server = mnt_ctx->server;
3531 unsigned int xid = mnt_ctx->xid;
3532 struct cifs_tcon *tcon = mnt_ctx->tcon;
3533 struct smb3_fs_context *ctx = mnt_ctx->fs_ctx;
3536 if (!server->ops->is_path_accessible)
3540 * cifs_build_path_to_root works only when we have a valid tcon
3542 full_path = cifs_build_path_to_root(ctx, cifs_sb, tcon,
3543 tcon->Flags & SMB_SHARE_IS_IN_DFS);
3544 if (full_path == NULL)
3547 cifs_dbg(FYI, "%s: full_path: %s\n", __func__, full_path);
3549 rc = server->ops->is_path_accessible(xid, tcon, cifs_sb,
3551 if (rc != 0 && rc != -EREMOTE)
3554 if (rc != -EREMOTE) {
3555 rc = cifs_are_all_path_components_accessible(server, xid, tcon,
3556 cifs_sb, full_path, tcon->Flags & SMB_SHARE_IS_IN_DFS);
3558 cifs_server_dbg(VFS, "cannot query dirs between root and final path, enabling CIFS_MOUNT_USE_PREFIX_PATH\n");
3559 cifs_sb->mnt_cifs_flags |= CIFS_MOUNT_USE_PREFIX_PATH;
3569 #ifdef CONFIG_CIFS_DFS_UPCALL
3570 int cifs_mount(struct cifs_sb_info *cifs_sb, struct smb3_fs_context *ctx)
3572 struct cifs_mount_ctx mnt_ctx = { .cifs_sb = cifs_sb, .fs_ctx = ctx, };
3576 INIT_LIST_HEAD(&mnt_ctx.dfs_ses_list);
3578 rc = dfs_mount_share(&mnt_ctx, &isdfs);
3585 * After reconnecting to a different server, unique ids won't match anymore, so we disable
3586 * serverino. This prevents dentry revalidation to think the dentry are stale (ESTALE).
3588 cifs_autodisable_serverino(cifs_sb);
3590 * Force the use of prefix path to support failover on DFS paths that resolve to targets
3591 * that have different prefix paths.
3593 cifs_sb->mnt_cifs_flags |= CIFS_MOUNT_USE_PREFIX_PATH;
3594 kfree(cifs_sb->prepath);
3595 cifs_sb->prepath = ctx->prepath;
3596 ctx->prepath = NULL;
3599 cifs_try_adding_channels(mnt_ctx.ses);
3600 rc = mount_setup_tlink(cifs_sb, mnt_ctx.ses, mnt_ctx.tcon);
3604 free_xid(mnt_ctx.xid);
3608 dfs_put_root_smb_sessions(&mnt_ctx.dfs_ses_list);
3609 cifs_mount_put_conns(&mnt_ctx);
3613 int cifs_mount(struct cifs_sb_info *cifs_sb, struct smb3_fs_context *ctx)
3616 struct cifs_mount_ctx mnt_ctx = { .cifs_sb = cifs_sb, .fs_ctx = ctx, };
3618 rc = cifs_mount_get_session(&mnt_ctx);
3622 rc = cifs_mount_get_tcon(&mnt_ctx);
3626 rc = cifs_is_path_remote(&mnt_ctx);
3632 rc = mount_setup_tlink(cifs_sb, mnt_ctx.ses, mnt_ctx.tcon);
3636 free_xid(mnt_ctx.xid);
3640 cifs_mount_put_conns(&mnt_ctx);
3646 * Issue a TREE_CONNECT request.
3649 CIFSTCon(const unsigned int xid, struct cifs_ses *ses,
3650 const char *tree, struct cifs_tcon *tcon,
3651 const struct nls_table *nls_codepage)
3653 struct smb_hdr *smb_buffer;
3654 struct smb_hdr *smb_buffer_response;
3657 unsigned char *bcc_ptr;
3660 __u16 bytes_left, count;
3665 smb_buffer = cifs_buf_get();
3666 if (smb_buffer == NULL)
3669 smb_buffer_response = smb_buffer;
3671 header_assemble(smb_buffer, SMB_COM_TREE_CONNECT_ANDX,
3672 NULL /*no tid */ , 4 /*wct */ );
3674 smb_buffer->Mid = get_next_mid(ses->server);
3675 smb_buffer->Uid = ses->Suid;
3676 pSMB = (TCONX_REQ *) smb_buffer;
3677 pSMBr = (TCONX_RSP *) smb_buffer_response;
3679 pSMB->AndXCommand = 0xFF;
3680 pSMB->Flags = cpu_to_le16(TCON_EXTENDED_SECINFO);
3681 bcc_ptr = &pSMB->Password[0];
3683 pSMB->PasswordLength = cpu_to_le16(1); /* minimum */
3684 *bcc_ptr = 0; /* password is null byte */
3685 bcc_ptr++; /* skip password */
3686 /* already aligned so no need to do it below */
3688 if (ses->server->sign)
3689 smb_buffer->Flags2 |= SMBFLG2_SECURITY_SIGNATURE;
3691 if (ses->capabilities & CAP_STATUS32) {
3692 smb_buffer->Flags2 |= SMBFLG2_ERR_STATUS;
3694 if (ses->capabilities & CAP_DFS) {
3695 smb_buffer->Flags2 |= SMBFLG2_DFS;
3697 if (ses->capabilities & CAP_UNICODE) {
3698 smb_buffer->Flags2 |= SMBFLG2_UNICODE;
3700 cifs_strtoUTF16((__le16 *) bcc_ptr, tree,
3701 6 /* max utf8 char length in bytes */ *
3702 (/* server len*/ + 256 /* share len */), nls_codepage);
3703 bcc_ptr += 2 * length; /* convert num 16 bit words to bytes */
3704 bcc_ptr += 2; /* skip trailing null */
3705 } else { /* ASCII */
3706 strcpy(bcc_ptr, tree);
3707 bcc_ptr += strlen(tree) + 1;
3709 strcpy(bcc_ptr, "?????");
3710 bcc_ptr += strlen("?????");
3712 count = bcc_ptr - &pSMB->Password[0];
3713 be32_add_cpu(&pSMB->hdr.smb_buf_length, count);
3714 pSMB->ByteCount = cpu_to_le16(count);
3716 rc = SendReceive(xid, ses, smb_buffer, smb_buffer_response, &length,
3719 /* above now done in SendReceive */
3723 tcon->tid = smb_buffer_response->Tid;
3724 bcc_ptr = pByteArea(smb_buffer_response);
3725 bytes_left = get_bcc(smb_buffer_response);
3726 length = strnlen(bcc_ptr, bytes_left - 2);
3727 if (smb_buffer->Flags2 & SMBFLG2_UNICODE)
3733 /* skip service field (NB: this field is always ASCII) */
3735 if ((bcc_ptr[0] == 'I') && (bcc_ptr[1] == 'P') &&
3736 (bcc_ptr[2] == 'C')) {
3737 cifs_dbg(FYI, "IPC connection\n");
3741 } else if (length == 2) {
3742 if ((bcc_ptr[0] == 'A') && (bcc_ptr[1] == ':')) {
3743 /* the most common case */
3744 cifs_dbg(FYI, "disk share connection\n");
3747 bcc_ptr += length + 1;
3748 bytes_left -= (length + 1);
3749 strscpy(tcon->tree_name, tree, sizeof(tcon->tree_name));
3751 /* mostly informational -- no need to fail on error here */
3752 kfree(tcon->nativeFileSystem);
3753 tcon->nativeFileSystem = cifs_strndup_from_utf16(bcc_ptr,
3754 bytes_left, is_unicode,
3757 cifs_dbg(FYI, "nativeFileSystem=%s\n", tcon->nativeFileSystem);
3759 if ((smb_buffer_response->WordCount == 3) ||
3760 (smb_buffer_response->WordCount == 7))
3761 /* field is in same location */
3762 tcon->Flags = le16_to_cpu(pSMBr->OptionalSupport);
3765 cifs_dbg(FYI, "Tcon flags: 0x%x\n", tcon->Flags);
3768 cifs_buf_release(smb_buffer);
3772 static void delayed_free(struct rcu_head *p)
3774 struct cifs_sb_info *cifs_sb = container_of(p, struct cifs_sb_info, rcu);
3776 unload_nls(cifs_sb->local_nls);
3777 smb3_cleanup_fs_context(cifs_sb->ctx);
3782 cifs_umount(struct cifs_sb_info *cifs_sb)
3784 struct rb_root *root = &cifs_sb->tlink_tree;
3785 struct rb_node *node;
3786 struct tcon_link *tlink;
3788 cancel_delayed_work_sync(&cifs_sb->prune_tlinks);
3790 spin_lock(&cifs_sb->tlink_tree_lock);
3791 while ((node = rb_first(root))) {
3792 tlink = rb_entry(node, struct tcon_link, tl_rbnode);
3793 cifs_get_tlink(tlink);
3794 clear_bit(TCON_LINK_IN_TREE, &tlink->tl_flags);
3795 rb_erase(node, root);
3797 spin_unlock(&cifs_sb->tlink_tree_lock);
3798 cifs_put_tlink(tlink);
3799 spin_lock(&cifs_sb->tlink_tree_lock);
3801 spin_unlock(&cifs_sb->tlink_tree_lock);
3803 kfree(cifs_sb->prepath);
3804 call_rcu(&cifs_sb->rcu, delayed_free);
3808 cifs_negotiate_protocol(const unsigned int xid, struct cifs_ses *ses,
3809 struct TCP_Server_Info *server)
3813 if (!server->ops->need_neg || !server->ops->negotiate)
3816 /* only send once per connect */
3817 spin_lock(&server->srv_lock);
3818 if (server->tcpStatus != CifsGood &&
3819 server->tcpStatus != CifsNew &&
3820 server->tcpStatus != CifsNeedNegotiate) {
3821 spin_unlock(&server->srv_lock);
3825 if (!server->ops->need_neg(server) &&
3826 server->tcpStatus == CifsGood) {
3827 spin_unlock(&server->srv_lock);
3831 server->tcpStatus = CifsInNegotiate;
3832 spin_unlock(&server->srv_lock);
3834 rc = server->ops->negotiate(xid, ses, server);
3836 spin_lock(&server->srv_lock);
3837 if (server->tcpStatus == CifsInNegotiate)
3838 server->tcpStatus = CifsGood;
3841 spin_unlock(&server->srv_lock);
3843 spin_lock(&server->srv_lock);
3844 if (server->tcpStatus == CifsInNegotiate)
3845 server->tcpStatus = CifsNeedNegotiate;
3846 spin_unlock(&server->srv_lock);
3853 cifs_setup_session(const unsigned int xid, struct cifs_ses *ses,
3854 struct TCP_Server_Info *server,
3855 struct nls_table *nls_info)
3858 struct TCP_Server_Info *pserver = SERVER_IS_CHAN(server) ? server->primary_server : server;
3859 struct sockaddr_in6 *addr6 = (struct sockaddr_in6 *)&pserver->dstaddr;
3860 struct sockaddr_in *addr = (struct sockaddr_in *)&pserver->dstaddr;
3861 bool is_binding = false;
3863 spin_lock(&ses->ses_lock);
3864 cifs_dbg(FYI, "%s: channel connect bitmap: 0x%lx\n",
3865 __func__, ses->chans_need_reconnect);
3867 if (ses->ses_status != SES_GOOD &&
3868 ses->ses_status != SES_NEW &&
3869 ses->ses_status != SES_NEED_RECON) {
3870 spin_unlock(&ses->ses_lock);
3874 /* only send once per connect */
3875 spin_lock(&ses->chan_lock);
3876 if (CIFS_ALL_CHANS_GOOD(ses)) {
3877 if (ses->ses_status == SES_NEED_RECON)
3878 ses->ses_status = SES_GOOD;
3879 spin_unlock(&ses->chan_lock);
3880 spin_unlock(&ses->ses_lock);
3884 cifs_chan_set_in_reconnect(ses, server);
3885 is_binding = !CIFS_ALL_CHANS_NEED_RECONNECT(ses);
3886 spin_unlock(&ses->chan_lock);
3889 ses->ses_status = SES_IN_SETUP;
3891 /* force iface_list refresh */
3892 ses->iface_last_update = 0;
3894 spin_unlock(&ses->ses_lock);
3896 /* update ses ip_addr only for primary chan */
3897 if (server == pserver) {
3898 if (server->dstaddr.ss_family == AF_INET6)
3899 scnprintf(ses->ip_addr, sizeof(ses->ip_addr), "%pI6", &addr6->sin6_addr);
3901 scnprintf(ses->ip_addr, sizeof(ses->ip_addr), "%pI4", &addr->sin_addr);
3905 ses->capabilities = server->capabilities;
3906 if (!linuxExtEnabled)
3907 ses->capabilities &= (~server->vals->cap_unix);
3909 if (ses->auth_key.response) {
3910 cifs_dbg(FYI, "Free previous auth_key.response = %p\n",
3911 ses->auth_key.response);
3912 kfree_sensitive(ses->auth_key.response);
3913 ses->auth_key.response = NULL;
3914 ses->auth_key.len = 0;
3918 cifs_dbg(FYI, "Security Mode: 0x%x Capabilities: 0x%x TimeAdjust: %d\n",
3919 server->sec_mode, server->capabilities, server->timeAdj);
3921 if (server->ops->sess_setup)
3922 rc = server->ops->sess_setup(xid, ses, server, nls_info);
3925 cifs_server_dbg(VFS, "Send error in SessSetup = %d\n", rc);
3926 spin_lock(&ses->ses_lock);
3927 if (ses->ses_status == SES_IN_SETUP)
3928 ses->ses_status = SES_NEED_RECON;
3929 spin_lock(&ses->chan_lock);
3930 cifs_chan_clear_in_reconnect(ses, server);
3931 spin_unlock(&ses->chan_lock);
3932 spin_unlock(&ses->ses_lock);
3934 spin_lock(&ses->ses_lock);
3935 if (ses->ses_status == SES_IN_SETUP)
3936 ses->ses_status = SES_GOOD;
3937 spin_lock(&ses->chan_lock);
3938 cifs_chan_clear_in_reconnect(ses, server);
3939 cifs_chan_clear_need_reconnect(ses, server);
3940 spin_unlock(&ses->chan_lock);
3941 spin_unlock(&ses->ses_lock);
3948 cifs_set_vol_auth(struct smb3_fs_context *ctx, struct cifs_ses *ses)
3950 ctx->sectype = ses->sectype;
3952 /* krb5 is special, since we don't need username or pw */
3953 if (ctx->sectype == Kerberos)
3956 return cifs_set_cifscreds(ctx, ses);
3959 static struct cifs_tcon *
3960 cifs_construct_tcon(struct cifs_sb_info *cifs_sb, kuid_t fsuid)
3963 struct cifs_tcon *master_tcon = cifs_sb_master_tcon(cifs_sb);
3964 struct cifs_ses *ses;
3965 struct cifs_tcon *tcon = NULL;
3966 struct smb3_fs_context *ctx;
3968 ctx = kzalloc(sizeof(*ctx), GFP_KERNEL);
3970 return ERR_PTR(-ENOMEM);
3972 ctx->local_nls = cifs_sb->local_nls;
3973 ctx->linux_uid = fsuid;
3974 ctx->cred_uid = fsuid;
3975 ctx->UNC = master_tcon->tree_name;
3976 ctx->retry = master_tcon->retry;
3977 ctx->nocase = master_tcon->nocase;
3978 ctx->nohandlecache = master_tcon->nohandlecache;
3979 ctx->local_lease = master_tcon->local_lease;
3980 ctx->no_lease = master_tcon->no_lease;
3981 ctx->resilient = master_tcon->use_resilient;
3982 ctx->persistent = master_tcon->use_persistent;
3983 ctx->handle_timeout = master_tcon->handle_timeout;
3984 ctx->no_linux_ext = !master_tcon->unix_ext;
3985 ctx->linux_ext = master_tcon->posix_extensions;
3986 ctx->sectype = master_tcon->ses->sectype;
3987 ctx->sign = master_tcon->ses->sign;
3988 ctx->seal = master_tcon->seal;
3989 ctx->witness = master_tcon->use_witness;
3991 rc = cifs_set_vol_auth(ctx, master_tcon->ses);
3997 /* get a reference for the same TCP session */
3998 spin_lock(&cifs_tcp_ses_lock);
3999 ++master_tcon->ses->server->srv_count;
4000 spin_unlock(&cifs_tcp_ses_lock);
4002 ses = cifs_get_smb_ses(master_tcon->ses->server, ctx);
4004 tcon = (struct cifs_tcon *)ses;
4005 cifs_put_tcp_session(master_tcon->ses->server, 0);
4009 tcon = cifs_get_tcon(ses, ctx);
4011 cifs_put_smb_ses(ses);
4015 #ifdef CONFIG_CIFS_ALLOW_INSECURE_LEGACY
4017 reset_cifs_unix_caps(0, tcon, NULL, ctx);
4018 #endif /* CONFIG_CIFS_ALLOW_INSECURE_LEGACY */
4021 kfree(ctx->username);
4022 kfree_sensitive(ctx->password);
4029 cifs_sb_master_tcon(struct cifs_sb_info *cifs_sb)
4031 return tlink_tcon(cifs_sb_master_tlink(cifs_sb));
4034 /* find and return a tlink with given uid */
4035 static struct tcon_link *
4036 tlink_rb_search(struct rb_root *root, kuid_t uid)
4038 struct rb_node *node = root->rb_node;
4039 struct tcon_link *tlink;
4042 tlink = rb_entry(node, struct tcon_link, tl_rbnode);
4044 if (uid_gt(tlink->tl_uid, uid))
4045 node = node->rb_left;
4046 else if (uid_lt(tlink->tl_uid, uid))
4047 node = node->rb_right;
4054 /* insert a tcon_link into the tree */
4056 tlink_rb_insert(struct rb_root *root, struct tcon_link *new_tlink)
4058 struct rb_node **new = &(root->rb_node), *parent = NULL;
4059 struct tcon_link *tlink;
4062 tlink = rb_entry(*new, struct tcon_link, tl_rbnode);
4065 if (uid_gt(tlink->tl_uid, new_tlink->tl_uid))
4066 new = &((*new)->rb_left);
4068 new = &((*new)->rb_right);
4071 rb_link_node(&new_tlink->tl_rbnode, parent, new);
4072 rb_insert_color(&new_tlink->tl_rbnode, root);
4076 * Find or construct an appropriate tcon given a cifs_sb and the fsuid of the
4079 * If the superblock doesn't refer to a multiuser mount, then just return
4080 * the master tcon for the mount.
4082 * First, search the rbtree for an existing tcon for this fsuid. If one
4083 * exists, then check to see if it's pending construction. If it is then wait
4084 * for construction to complete. Once it's no longer pending, check to see if
4085 * it failed and either return an error or retry construction, depending on
4088 * If one doesn't exist then insert a new tcon_link struct into the tree and
4089 * try to construct a new one.
4092 cifs_sb_tlink(struct cifs_sb_info *cifs_sb)
4095 kuid_t fsuid = current_fsuid();
4096 struct tcon_link *tlink, *newtlink;
4098 if (!(cifs_sb->mnt_cifs_flags & CIFS_MOUNT_MULTIUSER))
4099 return cifs_get_tlink(cifs_sb_master_tlink(cifs_sb));
4101 spin_lock(&cifs_sb->tlink_tree_lock);
4102 tlink = tlink_rb_search(&cifs_sb->tlink_tree, fsuid);
4104 cifs_get_tlink(tlink);
4105 spin_unlock(&cifs_sb->tlink_tree_lock);
4107 if (tlink == NULL) {
4108 newtlink = kzalloc(sizeof(*tlink), GFP_KERNEL);
4109 if (newtlink == NULL)
4110 return ERR_PTR(-ENOMEM);
4111 newtlink->tl_uid = fsuid;
4112 newtlink->tl_tcon = ERR_PTR(-EACCES);
4113 set_bit(TCON_LINK_PENDING, &newtlink->tl_flags);
4114 set_bit(TCON_LINK_IN_TREE, &newtlink->tl_flags);
4115 cifs_get_tlink(newtlink);
4117 spin_lock(&cifs_sb->tlink_tree_lock);
4118 /* was one inserted after previous search? */
4119 tlink = tlink_rb_search(&cifs_sb->tlink_tree, fsuid);
4121 cifs_get_tlink(tlink);
4122 spin_unlock(&cifs_sb->tlink_tree_lock);
4124 goto wait_for_construction;
4127 tlink_rb_insert(&cifs_sb->tlink_tree, tlink);
4128 spin_unlock(&cifs_sb->tlink_tree_lock);
4130 wait_for_construction:
4131 ret = wait_on_bit(&tlink->tl_flags, TCON_LINK_PENDING,
4132 TASK_INTERRUPTIBLE);
4134 cifs_put_tlink(tlink);
4135 return ERR_PTR(-ERESTARTSYS);
4138 /* if it's good, return it */
4139 if (!IS_ERR(tlink->tl_tcon))
4142 /* return error if we tried this already recently */
4143 if (time_before(jiffies, tlink->tl_time + TLINK_ERROR_EXPIRE)) {
4144 cifs_put_tlink(tlink);
4145 return ERR_PTR(-EACCES);
4148 if (test_and_set_bit(TCON_LINK_PENDING, &tlink->tl_flags))
4149 goto wait_for_construction;
4152 tlink->tl_tcon = cifs_construct_tcon(cifs_sb, fsuid);
4153 clear_bit(TCON_LINK_PENDING, &tlink->tl_flags);
4154 wake_up_bit(&tlink->tl_flags, TCON_LINK_PENDING);
4156 if (IS_ERR(tlink->tl_tcon)) {
4157 cifs_put_tlink(tlink);
4158 return ERR_PTR(-EACCES);
4165 * periodic workqueue job that scans tcon_tree for a superblock and closes
4169 cifs_prune_tlinks(struct work_struct *work)
4171 struct cifs_sb_info *cifs_sb = container_of(work, struct cifs_sb_info,
4173 struct rb_root *root = &cifs_sb->tlink_tree;
4174 struct rb_node *node;
4175 struct rb_node *tmp;
4176 struct tcon_link *tlink;
4179 * Because we drop the spinlock in the loop in order to put the tlink
4180 * it's not guarded against removal of links from the tree. The only
4181 * places that remove entries from the tree are this function and
4182 * umounts. Because this function is non-reentrant and is canceled
4183 * before umount can proceed, this is safe.
4185 spin_lock(&cifs_sb->tlink_tree_lock);
4186 node = rb_first(root);
4187 while (node != NULL) {
4189 node = rb_next(tmp);
4190 tlink = rb_entry(tmp, struct tcon_link, tl_rbnode);
4192 if (test_bit(TCON_LINK_MASTER, &tlink->tl_flags) ||
4193 atomic_read(&tlink->tl_count) != 0 ||
4194 time_after(tlink->tl_time + TLINK_IDLE_EXPIRE, jiffies))
4197 cifs_get_tlink(tlink);
4198 clear_bit(TCON_LINK_IN_TREE, &tlink->tl_flags);
4199 rb_erase(tmp, root);
4201 spin_unlock(&cifs_sb->tlink_tree_lock);
4202 cifs_put_tlink(tlink);
4203 spin_lock(&cifs_sb->tlink_tree_lock);
4205 spin_unlock(&cifs_sb->tlink_tree_lock);
4207 queue_delayed_work(cifsiod_wq, &cifs_sb->prune_tlinks,
4211 #ifndef CONFIG_CIFS_DFS_UPCALL
4212 int cifs_tree_connect(const unsigned int xid, struct cifs_tcon *tcon, const struct nls_table *nlsc)
4215 const struct smb_version_operations *ops = tcon->ses->server->ops;
4217 /* only send once per connect */
4218 spin_lock(&tcon->tc_lock);
4219 if (tcon->status == TID_GOOD) {
4220 spin_unlock(&tcon->tc_lock);
4224 if (tcon->status != TID_NEW &&
4225 tcon->status != TID_NEED_TCON) {
4226 spin_unlock(&tcon->tc_lock);
4230 tcon->status = TID_IN_TCON;
4231 spin_unlock(&tcon->tc_lock);
4233 rc = ops->tree_connect(xid, tcon->ses, tcon->tree_name, tcon, nlsc);
4235 spin_lock(&tcon->tc_lock);
4236 if (tcon->status == TID_IN_TCON)
4237 tcon->status = TID_NEED_TCON;
4238 spin_unlock(&tcon->tc_lock);
4240 spin_lock(&tcon->tc_lock);
4241 if (tcon->status == TID_IN_TCON)
4242 tcon->status = TID_GOOD;
4243 tcon->need_reconnect = false;
4244 spin_unlock(&tcon->tc_lock);