1 // SPDX-License-Identifier: LGPL-2.1
4 * Copyright (C) International Business Machines Corp., 2002,2011
10 #include <linux/string.h>
11 #include <linux/sched/mm.h>
12 #include <linux/sched/signal.h>
13 #include <linux/list.h>
14 #include <linux/wait.h>
15 #include <linux/slab.h>
16 #include <linux/pagemap.h>
17 #include <linux/ctype.h>
18 #include <linux/utsname.h>
19 #include <linux/mempool.h>
20 #include <linux/delay.h>
21 #include <linux/completion.h>
22 #include <linux/kthread.h>
23 #include <linux/pagevec.h>
24 #include <linux/freezer.h>
25 #include <linux/namei.h>
26 #include <linux/uuid.h>
27 #include <linux/uaccess.h>
28 #include <asm/processor.h>
29 #include <linux/inet.h>
30 #include <linux/module.h>
31 #include <keys/user-type.h>
33 #include <linux/parser.h>
34 #include <linux/bvec.h>
37 #include "cifsproto.h"
38 #include "cifs_unicode.h"
39 #include "cifs_debug.h"
40 #include "cifs_fs_sb.h"
43 #include "rfc1002pdu.h"
45 #include "smb2proto.h"
46 #include "smbdirect.h"
47 #include "dns_resolve.h"
48 #ifdef CONFIG_CIFS_DFS_UPCALL
49 #include "dfs_cache.h"
51 #include "fs_context.h"
54 extern mempool_t *cifs_req_poolp;
55 extern bool disable_legacy_dialects;
57 /* FIXME: should these be tunable? */
58 #define TLINK_ERROR_EXPIRE (1 * HZ)
59 #define TLINK_IDLE_EXPIRE (600 * HZ)
61 /* Drop the connection to not overload the server */
62 #define NUM_STATUS_IO_TIMEOUT 5
65 struct cifs_sb_info *cifs_sb;
66 struct smb3_fs_context *fs_ctx;
68 struct TCP_Server_Info *server;
70 struct cifs_tcon *tcon;
71 #ifdef CONFIG_CIFS_DFS_UPCALL
72 struct cifs_ses *root_ses;
74 char *origin_fullpath, *leaf_fullpath;
78 static int ip_connect(struct TCP_Server_Info *server);
79 static int generic_ip_connect(struct TCP_Server_Info *server);
80 static void tlink_rb_insert(struct rb_root *root, struct tcon_link *new_tlink);
81 static void cifs_prune_tlinks(struct work_struct *work);
84 * Resolve hostname and set ip addr in tcp ses. Useful for hostnames that may
85 * get their ip addresses changed at some point.
87 * This should be called with server->srv_mutex held.
89 static int reconn_set_ipaddr_from_hostname(struct TCP_Server_Info *server)
93 char *unc, *ipaddr = NULL;
95 unsigned long ttl = SMB_DNS_RESOLVE_INTERVAL_DEFAULT;
97 if (!server->hostname)
100 len = strlen(server->hostname) + 3;
102 unc = kmalloc(len, GFP_KERNEL);
104 cifs_dbg(FYI, "%s: failed to create UNC path\n", __func__);
107 scnprintf(unc, len, "\\\\%s", server->hostname);
109 rc = dns_resolve_server_name_to_ip(unc, &ipaddr, &expiry);
113 cifs_dbg(FYI, "%s: failed to resolve server part of %s to IP: %d\n",
114 __func__, server->hostname, rc);
115 goto requeue_resolve;
118 spin_lock(&cifs_tcp_ses_lock);
119 rc = cifs_convert_address((struct sockaddr *)&server->dstaddr, ipaddr,
121 spin_unlock(&cifs_tcp_ses_lock);
124 /* rc == 1 means success here */
126 now = ktime_get_real_seconds();
127 if (expiry && expiry > now)
129 * To make sure we don't use the cached entry, retry 1s
132 ttl = max_t(unsigned long, expiry - now, SMB_DNS_RESOLVE_INTERVAL_MIN) + 1;
137 cifs_dbg(FYI, "%s: next dns resolution scheduled for %lu seconds in the future\n",
139 mod_delayed_work(cifsiod_wq, &server->resolve, (ttl * HZ));
145 static void cifs_resolve_server(struct work_struct *work)
148 struct TCP_Server_Info *server = container_of(work,
149 struct TCP_Server_Info, resolve.work);
151 mutex_lock(&server->srv_mutex);
154 * Resolve the hostname again to make sure that IP address is up-to-date.
156 rc = reconn_set_ipaddr_from_hostname(server);
158 cifs_dbg(FYI, "%s: failed to resolve hostname: %d\n",
162 mutex_unlock(&server->srv_mutex);
166 * Update the tcpStatus for the server.
167 * This is used to signal the cifsd thread to call cifs_reconnect
168 * ONLY cifsd thread should call cifs_reconnect. For any other
169 * thread, use this function
171 * @server: the tcp ses for which reconnect is needed
172 * @all_channels: if this needs to be done for all channels
175 cifs_signal_cifsd_for_reconnect(struct TCP_Server_Info *server,
178 struct TCP_Server_Info *pserver;
179 struct cifs_ses *ses;
182 /* If server is a channel, select the primary channel */
183 pserver = CIFS_SERVER_IS_CHAN(server) ? server->primary_server : server;
185 spin_lock(&cifs_tcp_ses_lock);
187 pserver->tcpStatus = CifsNeedReconnect;
188 spin_unlock(&cifs_tcp_ses_lock);
192 list_for_each_entry(ses, &pserver->smb_ses_list, smb_ses_list) {
193 spin_lock(&ses->chan_lock);
194 for (i = 0; i < ses->chan_count; i++)
195 ses->chans[i].server->tcpStatus = CifsNeedReconnect;
196 spin_unlock(&ses->chan_lock);
198 spin_unlock(&cifs_tcp_ses_lock);
202 * Mark all sessions and tcons for reconnect.
203 * IMPORTANT: make sure that this gets called only from
204 * cifsd thread. For any other thread, use
205 * cifs_signal_cifsd_for_reconnect
207 * @server: the tcp ses for which reconnect is needed
208 * @server needs to be previously set to CifsNeedReconnect.
209 * @mark_smb_session: whether even sessions need to be marked
212 cifs_mark_tcp_ses_conns_for_reconnect(struct TCP_Server_Info *server,
213 bool mark_smb_session)
215 struct TCP_Server_Info *pserver;
216 struct cifs_ses *ses;
217 struct cifs_tcon *tcon;
220 * before reconnecting the tcp session, mark the smb session (uid) and the tid bad so they
221 * are not used until reconnected.
223 cifs_dbg(FYI, "%s: marking necessary sessions and tcons for reconnect\n", __func__);
225 /* If server is a channel, select the primary channel */
226 pserver = CIFS_SERVER_IS_CHAN(server) ? server->primary_server : server;
229 spin_lock(&cifs_tcp_ses_lock);
230 list_for_each_entry(ses, &pserver->smb_ses_list, smb_ses_list) {
231 spin_lock(&ses->chan_lock);
232 if (!mark_smb_session && cifs_chan_needs_reconnect(ses, server))
235 if (mark_smb_session)
236 CIFS_SET_ALL_CHANS_NEED_RECONNECT(ses);
238 cifs_chan_set_need_reconnect(ses, server);
240 /* If all channels need reconnect, then tcon needs reconnect */
241 if (!mark_smb_session && !CIFS_ALL_CHANS_NEED_RECONNECT(ses))
244 ses->status = CifsNeedReconnect;
246 list_for_each_entry(tcon, &ses->tcon_list, tcon_list) {
247 tcon->need_reconnect = true;
248 tcon->status = TID_NEED_RECON;
251 ses->tcon_ipc->need_reconnect = true;
254 spin_unlock(&ses->chan_lock);
256 spin_unlock(&cifs_tcp_ses_lock);
260 cifs_abort_connection(struct TCP_Server_Info *server)
262 struct mid_q_entry *mid, *nmid;
263 struct list_head retry_list;
266 server->max_read = 0;
268 /* do not want to be sending data on a socket we are freeing */
269 cifs_dbg(FYI, "%s: tearing down socket\n", __func__);
270 mutex_lock(&server->srv_mutex);
271 if (server->ssocket) {
272 cifs_dbg(FYI, "State: 0x%x Flags: 0x%lx\n", server->ssocket->state,
273 server->ssocket->flags);
274 kernel_sock_shutdown(server->ssocket, SHUT_WR);
275 cifs_dbg(FYI, "Post shutdown state: 0x%x Flags: 0x%lx\n", server->ssocket->state,
276 server->ssocket->flags);
277 sock_release(server->ssocket);
278 server->ssocket = NULL;
280 server->sequence_number = 0;
281 server->session_estab = false;
282 kfree(server->session_key.response);
283 server->session_key.response = NULL;
284 server->session_key.len = 0;
285 server->lstrp = jiffies;
287 /* mark submitted MIDs for retry and issue callback */
288 INIT_LIST_HEAD(&retry_list);
289 cifs_dbg(FYI, "%s: moving mids to private list\n", __func__);
290 spin_lock(&GlobalMid_Lock);
291 list_for_each_entry_safe(mid, nmid, &server->pending_mid_q, qhead) {
292 kref_get(&mid->refcount);
293 if (mid->mid_state == MID_REQUEST_SUBMITTED)
294 mid->mid_state = MID_RETRY_NEEDED;
295 list_move(&mid->qhead, &retry_list);
296 mid->mid_flags |= MID_DELETED;
298 spin_unlock(&GlobalMid_Lock);
299 mutex_unlock(&server->srv_mutex);
301 cifs_dbg(FYI, "%s: issuing mid callbacks\n", __func__);
302 list_for_each_entry_safe(mid, nmid, &retry_list, qhead) {
303 list_del_init(&mid->qhead);
305 cifs_mid_q_entry_release(mid);
308 if (cifs_rdma_enabled(server)) {
309 mutex_lock(&server->srv_mutex);
310 smbd_destroy(server);
311 mutex_unlock(&server->srv_mutex);
315 static bool cifs_tcp_ses_needs_reconnect(struct TCP_Server_Info *server, int num_targets)
317 spin_lock(&cifs_tcp_ses_lock);
318 server->nr_targets = num_targets;
319 if (server->tcpStatus == CifsExiting) {
320 /* the demux thread will exit normally next time through the loop */
321 spin_unlock(&cifs_tcp_ses_lock);
322 wake_up(&server->response_q);
326 cifs_dbg(FYI, "Mark tcp session as need reconnect\n");
327 trace_smb3_reconnect(server->CurrentMid, server->conn_id,
329 server->tcpStatus = CifsNeedReconnect;
331 spin_unlock(&cifs_tcp_ses_lock);
336 * cifs tcp session reconnection
338 * mark tcp session as reconnecting so temporarily locked
339 * mark all smb sessions as reconnecting for tcp session
340 * reconnect tcp session
341 * wake up waiters on reconnection? - (not needed currently)
343 * if mark_smb_session is passed as true, unconditionally mark
344 * the smb session (and tcon) for reconnect as well. This value
345 * doesn't really matter for non-multichannel scenario.
348 static int __cifs_reconnect(struct TCP_Server_Info *server,
349 bool mark_smb_session)
353 if (!cifs_tcp_ses_needs_reconnect(server, 1))
356 cifs_mark_tcp_ses_conns_for_reconnect(server, mark_smb_session);
358 cifs_abort_connection(server);
362 mutex_lock(&server->srv_mutex);
364 if (!cifs_swn_set_server_dstaddr(server)) {
365 /* resolve the hostname again to make sure that IP address is up-to-date */
366 rc = reconn_set_ipaddr_from_hostname(server);
367 cifs_dbg(FYI, "%s: reconn_set_ipaddr_from_hostname: rc=%d\n", __func__, rc);
370 if (cifs_rdma_enabled(server))
371 rc = smbd_reconnect(server);
373 rc = generic_ip_connect(server);
375 mutex_unlock(&server->srv_mutex);
376 cifs_dbg(FYI, "%s: reconnect error %d\n", __func__, rc);
379 atomic_inc(&tcpSesReconnectCount);
380 set_credits(server, 1);
381 spin_lock(&cifs_tcp_ses_lock);
382 if (server->tcpStatus != CifsExiting)
383 server->tcpStatus = CifsNeedNegotiate;
384 spin_unlock(&cifs_tcp_ses_lock);
385 cifs_swn_reset_server_dstaddr(server);
386 mutex_unlock(&server->srv_mutex);
387 mod_delayed_work(cifsiod_wq, &server->reconnect, 0);
389 } while (server->tcpStatus == CifsNeedReconnect);
391 spin_lock(&cifs_tcp_ses_lock);
392 if (server->tcpStatus == CifsNeedNegotiate)
393 mod_delayed_work(cifsiod_wq, &server->echo, 0);
394 spin_unlock(&cifs_tcp_ses_lock);
396 wake_up(&server->response_q);
400 #ifdef CONFIG_CIFS_DFS_UPCALL
401 static int __reconnect_target_unlocked(struct TCP_Server_Info *server, const char *target)
406 if (!cifs_swn_set_server_dstaddr(server)) {
407 if (server->hostname != target) {
408 hostname = extract_hostname(target);
409 if (!IS_ERR(hostname)) {
410 kfree(server->hostname);
411 server->hostname = hostname;
413 cifs_dbg(FYI, "%s: couldn't extract hostname or address from dfs target: %ld\n",
414 __func__, PTR_ERR(hostname));
415 cifs_dbg(FYI, "%s: default to last target server: %s\n", __func__,
419 /* resolve the hostname again to make sure that IP address is up-to-date. */
420 rc = reconn_set_ipaddr_from_hostname(server);
421 cifs_dbg(FYI, "%s: reconn_set_ipaddr_from_hostname: rc=%d\n", __func__, rc);
423 /* Reconnect the socket */
424 if (cifs_rdma_enabled(server))
425 rc = smbd_reconnect(server);
427 rc = generic_ip_connect(server);
432 static int reconnect_target_unlocked(struct TCP_Server_Info *server, struct dfs_cache_tgt_list *tl,
433 struct dfs_cache_tgt_iterator **target_hint)
436 struct dfs_cache_tgt_iterator *tit;
440 /* If dfs target list is empty, then reconnect to last server */
441 tit = dfs_cache_get_tgt_iterator(tl);
443 return __reconnect_target_unlocked(server, server->hostname);
445 /* Otherwise, try every dfs target in @tl */
446 for (; tit; tit = dfs_cache_get_next_tgt(tl, tit)) {
447 rc = __reconnect_target_unlocked(server, dfs_cache_get_tgt_name(tit));
457 reconnect_dfs_server(struct TCP_Server_Info *server,
458 bool mark_smb_session)
461 const char *refpath = server->current_fullpath + 1;
462 struct dfs_cache_tgt_list tl = DFS_CACHE_TGT_LIST_INIT(tl);
463 struct dfs_cache_tgt_iterator *target_hint = NULL;
467 * Determine the number of dfs targets the referral path in @cifs_sb resolves to.
469 * smb2_reconnect() needs to know how long it should wait based upon the number of dfs
470 * targets (server->nr_targets). It's also possible that the cached referral was cleared
471 * through /proc/fs/cifs/dfscache or the target list is empty due to server settings after
472 * refreshing the referral, so, in this case, default it to 1.
474 if (!dfs_cache_noreq_find(refpath, NULL, &tl))
475 num_targets = dfs_cache_get_nr_tgts(&tl);
479 if (!cifs_tcp_ses_needs_reconnect(server, num_targets))
482 cifs_mark_tcp_ses_conns_for_reconnect(server, mark_smb_session);
484 cifs_abort_connection(server);
488 mutex_lock(&server->srv_mutex);
490 rc = reconnect_target_unlocked(server, &tl, &target_hint);
492 /* Failed to reconnect socket */
493 mutex_unlock(&server->srv_mutex);
494 cifs_dbg(FYI, "%s: reconnect error %d\n", __func__, rc);
499 * Socket was created. Update tcp session status to CifsNeedNegotiate so that a
500 * process waiting for reconnect will know it needs to re-establish session and tcon
501 * through the reconnected target server.
503 atomic_inc(&tcpSesReconnectCount);
504 set_credits(server, 1);
505 spin_lock(&cifs_tcp_ses_lock);
506 if (server->tcpStatus != CifsExiting)
507 server->tcpStatus = CifsNeedNegotiate;
508 spin_unlock(&cifs_tcp_ses_lock);
509 cifs_swn_reset_server_dstaddr(server);
510 mutex_unlock(&server->srv_mutex);
511 mod_delayed_work(cifsiod_wq, &server->reconnect, 0);
512 } while (server->tcpStatus == CifsNeedReconnect);
515 dfs_cache_noreq_update_tgthint(refpath, target_hint);
517 dfs_cache_free_tgts(&tl);
519 /* Need to set up echo worker again once connection has been established */
520 spin_lock(&cifs_tcp_ses_lock);
521 if (server->tcpStatus == CifsNeedNegotiate)
522 mod_delayed_work(cifsiod_wq, &server->echo, 0);
524 spin_unlock(&cifs_tcp_ses_lock);
526 wake_up(&server->response_q);
530 int cifs_reconnect(struct TCP_Server_Info *server, bool mark_smb_session)
532 /* If tcp session is not an dfs connection, then reconnect to last target server */
533 spin_lock(&cifs_tcp_ses_lock);
534 if (!server->is_dfs_conn || !server->origin_fullpath || !server->leaf_fullpath) {
535 spin_unlock(&cifs_tcp_ses_lock);
536 return __cifs_reconnect(server, mark_smb_session);
538 spin_unlock(&cifs_tcp_ses_lock);
540 return reconnect_dfs_server(server, mark_smb_session);
543 int cifs_reconnect(struct TCP_Server_Info *server, bool mark_smb_session)
545 return __cifs_reconnect(server, mark_smb_session);
550 cifs_echo_request(struct work_struct *work)
553 struct TCP_Server_Info *server = container_of(work,
554 struct TCP_Server_Info, echo.work);
557 * We cannot send an echo if it is disabled.
558 * Also, no need to ping if we got a response recently.
561 if (server->tcpStatus == CifsNeedReconnect ||
562 server->tcpStatus == CifsExiting ||
563 server->tcpStatus == CifsNew ||
564 (server->ops->can_echo && !server->ops->can_echo(server)) ||
565 time_before(jiffies, server->lstrp + server->echo_interval - HZ))
568 rc = server->ops->echo ? server->ops->echo(server) : -ENOSYS;
570 cifs_dbg(FYI, "Unable to send echo request to server: %s\n",
573 /* Check witness registrations */
577 queue_delayed_work(cifsiod_wq, &server->echo, server->echo_interval);
581 allocate_buffers(struct TCP_Server_Info *server)
583 if (!server->bigbuf) {
584 server->bigbuf = (char *)cifs_buf_get();
585 if (!server->bigbuf) {
586 cifs_server_dbg(VFS, "No memory for large SMB response\n");
588 /* retry will check if exiting */
591 } else if (server->large_buf) {
592 /* we are reusing a dirty large buf, clear its start */
593 memset(server->bigbuf, 0, HEADER_SIZE(server));
596 if (!server->smallbuf) {
597 server->smallbuf = (char *)cifs_small_buf_get();
598 if (!server->smallbuf) {
599 cifs_server_dbg(VFS, "No memory for SMB response\n");
601 /* retry will check if exiting */
604 /* beginning of smb buffer is cleared in our buf_get */
606 /* if existing small buf clear beginning */
607 memset(server->smallbuf, 0, HEADER_SIZE(server));
614 server_unresponsive(struct TCP_Server_Info *server)
617 * We need to wait 3 echo intervals to make sure we handle such
619 * 1s client sends a normal SMB request
620 * 2s client gets a response
621 * 30s echo workqueue job pops, and decides we got a response recently
622 * and don't need to send another
624 * 65s kernel_recvmsg times out, and we see that we haven't gotten
625 * a response in >60s.
627 spin_lock(&cifs_tcp_ses_lock);
628 if ((server->tcpStatus == CifsGood ||
629 server->tcpStatus == CifsNeedNegotiate) &&
630 (!server->ops->can_echo || server->ops->can_echo(server)) &&
631 time_after(jiffies, server->lstrp + 3 * server->echo_interval)) {
632 spin_unlock(&cifs_tcp_ses_lock);
633 cifs_server_dbg(VFS, "has not responded in %lu seconds. Reconnecting...\n",
634 (3 * server->echo_interval) / HZ);
635 cifs_reconnect(server, false);
638 spin_unlock(&cifs_tcp_ses_lock);
644 zero_credits(struct TCP_Server_Info *server)
648 spin_lock(&server->req_lock);
649 val = server->credits + server->echo_credits + server->oplock_credits;
650 if (server->in_flight == 0 && val == 0) {
651 spin_unlock(&server->req_lock);
654 spin_unlock(&server->req_lock);
659 cifs_readv_from_socket(struct TCP_Server_Info *server, struct msghdr *smb_msg)
664 smb_msg->msg_control = NULL;
665 smb_msg->msg_controllen = 0;
667 for (total_read = 0; msg_data_left(smb_msg); total_read += length) {
670 /* reconnect if no credits and no requests in flight */
671 if (zero_credits(server)) {
672 cifs_reconnect(server, false);
673 return -ECONNABORTED;
676 if (server_unresponsive(server))
677 return -ECONNABORTED;
678 if (cifs_rdma_enabled(server) && server->smbd_conn)
679 length = smbd_recv(server->smbd_conn, smb_msg);
681 length = sock_recvmsg(server->ssocket, smb_msg, 0);
683 spin_lock(&cifs_tcp_ses_lock);
684 if (server->tcpStatus == CifsExiting) {
685 spin_unlock(&cifs_tcp_ses_lock);
689 if (server->tcpStatus == CifsNeedReconnect) {
690 spin_unlock(&cifs_tcp_ses_lock);
691 cifs_reconnect(server, false);
692 return -ECONNABORTED;
694 spin_unlock(&cifs_tcp_ses_lock);
696 if (length == -ERESTARTSYS ||
700 * Minimum sleep to prevent looping, allowing socket
701 * to clear and app threads to set tcpStatus
702 * CifsNeedReconnect if server hung.
704 usleep_range(1000, 2000);
710 cifs_dbg(FYI, "Received no data or error: %d\n", length);
711 cifs_reconnect(server, false);
712 return -ECONNABORTED;
719 cifs_read_from_socket(struct TCP_Server_Info *server, char *buf,
720 unsigned int to_read)
722 struct msghdr smb_msg;
723 struct kvec iov = {.iov_base = buf, .iov_len = to_read};
724 iov_iter_kvec(&smb_msg.msg_iter, READ, &iov, 1, to_read);
726 return cifs_readv_from_socket(server, &smb_msg);
730 cifs_discard_from_socket(struct TCP_Server_Info *server, size_t to_read)
732 struct msghdr smb_msg;
735 * iov_iter_discard already sets smb_msg.type and count and iov_offset
736 * and cifs_readv_from_socket sets msg_control and msg_controllen
737 * so little to initialize in struct msghdr
739 smb_msg.msg_name = NULL;
740 smb_msg.msg_namelen = 0;
741 iov_iter_discard(&smb_msg.msg_iter, READ, to_read);
743 return cifs_readv_from_socket(server, &smb_msg);
747 cifs_read_page_from_socket(struct TCP_Server_Info *server, struct page *page,
748 unsigned int page_offset, unsigned int to_read)
750 struct msghdr smb_msg;
751 struct bio_vec bv = {
752 .bv_page = page, .bv_len = to_read, .bv_offset = page_offset};
753 iov_iter_bvec(&smb_msg.msg_iter, READ, &bv, 1, to_read);
754 return cifs_readv_from_socket(server, &smb_msg);
758 is_smb_response(struct TCP_Server_Info *server, unsigned char type)
761 * The first byte big endian of the length field,
762 * is actually not part of the length but the type
763 * with the most common, zero, as regular data.
766 case RFC1002_SESSION_MESSAGE:
767 /* Regular SMB response */
769 case RFC1002_SESSION_KEEP_ALIVE:
770 cifs_dbg(FYI, "RFC 1002 session keep alive\n");
772 case RFC1002_POSITIVE_SESSION_RESPONSE:
773 cifs_dbg(FYI, "RFC 1002 positive session response\n");
775 case RFC1002_NEGATIVE_SESSION_RESPONSE:
777 * We get this from Windows 98 instead of an error on
778 * SMB negprot response.
780 cifs_dbg(FYI, "RFC 1002 negative session response\n");
781 /* give server a second to clean up */
784 * Always try 445 first on reconnect since we get NACK
785 * on some if we ever connected to port 139 (the NACK
786 * is since we do not begin with RFC1001 session
789 cifs_set_port((struct sockaddr *)&server->dstaddr, CIFS_PORT);
790 cifs_reconnect(server, true);
793 cifs_server_dbg(VFS, "RFC 1002 unknown response type 0x%x\n", type);
794 cifs_reconnect(server, true);
801 dequeue_mid(struct mid_q_entry *mid, bool malformed)
803 #ifdef CONFIG_CIFS_STATS2
804 mid->when_received = jiffies;
806 spin_lock(&GlobalMid_Lock);
808 mid->mid_state = MID_RESPONSE_RECEIVED;
810 mid->mid_state = MID_RESPONSE_MALFORMED;
812 * Trying to handle/dequeue a mid after the send_recv()
813 * function has finished processing it is a bug.
815 if (mid->mid_flags & MID_DELETED) {
816 spin_unlock(&GlobalMid_Lock);
817 pr_warn_once("trying to dequeue a deleted mid\n");
819 list_del_init(&mid->qhead);
820 mid->mid_flags |= MID_DELETED;
821 spin_unlock(&GlobalMid_Lock);
826 smb2_get_credits_from_hdr(char *buffer, struct TCP_Server_Info *server)
828 struct smb2_hdr *shdr = (struct smb2_hdr *)buffer;
831 * SMB1 does not use credits.
833 if (server->vals->header_preamble_size)
836 return le16_to_cpu(shdr->CreditRequest);
840 handle_mid(struct mid_q_entry *mid, struct TCP_Server_Info *server,
841 char *buf, int malformed)
843 if (server->ops->check_trans2 &&
844 server->ops->check_trans2(mid, server, buf, malformed))
846 mid->credits_received = smb2_get_credits_from_hdr(buf, server);
848 mid->large_buf = server->large_buf;
849 /* Was previous buf put in mpx struct for multi-rsp? */
850 if (!mid->multiRsp) {
851 /* smb buffer will be freed by user thread */
852 if (server->large_buf)
853 server->bigbuf = NULL;
855 server->smallbuf = NULL;
857 dequeue_mid(mid, malformed);
860 static void clean_demultiplex_info(struct TCP_Server_Info *server)
864 /* take it off the list, if it's not already */
865 spin_lock(&cifs_tcp_ses_lock);
866 list_del_init(&server->tcp_ses_list);
867 spin_unlock(&cifs_tcp_ses_lock);
869 cancel_delayed_work_sync(&server->echo);
870 cancel_delayed_work_sync(&server->resolve);
872 spin_lock(&cifs_tcp_ses_lock);
873 server->tcpStatus = CifsExiting;
874 spin_unlock(&cifs_tcp_ses_lock);
875 wake_up_all(&server->response_q);
877 /* check if we have blocked requests that need to free */
878 spin_lock(&server->req_lock);
879 if (server->credits <= 0)
881 spin_unlock(&server->req_lock);
883 * Although there should not be any requests blocked on this queue it
884 * can not hurt to be paranoid and try to wake up requests that may
885 * haven been blocked when more than 50 at time were on the wire to the
886 * same server - they now will see the session is in exit state and get
887 * out of SendReceive.
889 wake_up_all(&server->request_q);
890 /* give those requests time to exit */
892 if (cifs_rdma_enabled(server))
893 smbd_destroy(server);
894 if (server->ssocket) {
895 sock_release(server->ssocket);
896 server->ssocket = NULL;
899 if (!list_empty(&server->pending_mid_q)) {
900 struct list_head dispose_list;
901 struct mid_q_entry *mid_entry;
902 struct list_head *tmp, *tmp2;
904 INIT_LIST_HEAD(&dispose_list);
905 spin_lock(&GlobalMid_Lock);
906 list_for_each_safe(tmp, tmp2, &server->pending_mid_q) {
907 mid_entry = list_entry(tmp, struct mid_q_entry, qhead);
908 cifs_dbg(FYI, "Clearing mid %llu\n", mid_entry->mid);
909 kref_get(&mid_entry->refcount);
910 mid_entry->mid_state = MID_SHUTDOWN;
911 list_move(&mid_entry->qhead, &dispose_list);
912 mid_entry->mid_flags |= MID_DELETED;
914 spin_unlock(&GlobalMid_Lock);
916 /* now walk dispose list and issue callbacks */
917 list_for_each_safe(tmp, tmp2, &dispose_list) {
918 mid_entry = list_entry(tmp, struct mid_q_entry, qhead);
919 cifs_dbg(FYI, "Callback mid %llu\n", mid_entry->mid);
920 list_del_init(&mid_entry->qhead);
921 mid_entry->callback(mid_entry);
922 cifs_mid_q_entry_release(mid_entry);
924 /* 1/8th of sec is more than enough time for them to exit */
928 if (!list_empty(&server->pending_mid_q)) {
930 * mpx threads have not exited yet give them at least the smb
931 * send timeout time for long ops.
933 * Due to delays on oplock break requests, we need to wait at
934 * least 45 seconds before giving up on a request getting a
935 * response and going ahead and killing cifsd.
937 cifs_dbg(FYI, "Wait for exit from demultiplex thread\n");
940 * If threads still have not exited they are probably never
941 * coming home not much else we can do but free the memory.
945 #ifdef CONFIG_CIFS_DFS_UPCALL
946 kfree(server->origin_fullpath);
947 kfree(server->leaf_fullpath);
951 length = atomic_dec_return(&tcpSesAllocCount);
953 mempool_resize(cifs_req_poolp, length + cifs_min_rcv);
957 standard_receive3(struct TCP_Server_Info *server, struct mid_q_entry *mid)
960 char *buf = server->smallbuf;
961 unsigned int pdu_length = server->pdu_size;
963 /* make sure this will fit in a large buffer */
964 if (pdu_length > CIFSMaxBufSize + MAX_HEADER_SIZE(server) -
965 server->vals->header_preamble_size) {
966 cifs_server_dbg(VFS, "SMB response too long (%u bytes)\n", pdu_length);
967 cifs_reconnect(server, true);
968 return -ECONNABORTED;
971 /* switch to large buffer if too big for a small one */
972 if (pdu_length > MAX_CIFS_SMALL_BUFFER_SIZE - 4) {
973 server->large_buf = true;
974 memcpy(server->bigbuf, buf, server->total_read);
975 buf = server->bigbuf;
978 /* now read the rest */
979 length = cifs_read_from_socket(server, buf + HEADER_SIZE(server) - 1,
980 pdu_length - HEADER_SIZE(server) + 1
981 + server->vals->header_preamble_size);
985 server->total_read += length;
987 dump_smb(buf, server->total_read);
989 return cifs_handle_standard(server, mid);
993 cifs_handle_standard(struct TCP_Server_Info *server, struct mid_q_entry *mid)
995 char *buf = server->large_buf ? server->bigbuf : server->smallbuf;
999 * We know that we received enough to get to the MID as we
1000 * checked the pdu_length earlier. Now check to see
1001 * if the rest of the header is OK. We borrow the length
1002 * var for the rest of the loop to avoid a new stack var.
1004 * 48 bytes is enough to display the header and a little bit
1005 * into the payload for debugging purposes.
1007 length = server->ops->check_message(buf, server->total_read, server);
1009 cifs_dump_mem("Bad SMB: ", buf,
1010 min_t(unsigned int, server->total_read, 48));
1012 if (server->ops->is_session_expired &&
1013 server->ops->is_session_expired(buf)) {
1014 cifs_reconnect(server, true);
1018 if (server->ops->is_status_pending &&
1019 server->ops->is_status_pending(buf, server))
1025 handle_mid(mid, server, buf, length);
1030 smb2_add_credits_from_hdr(char *buffer, struct TCP_Server_Info *server)
1032 struct smb2_hdr *shdr = (struct smb2_hdr *)buffer;
1033 int scredits, in_flight;
1036 * SMB1 does not use credits.
1038 if (server->vals->header_preamble_size)
1041 if (shdr->CreditRequest) {
1042 spin_lock(&server->req_lock);
1043 server->credits += le16_to_cpu(shdr->CreditRequest);
1044 scredits = server->credits;
1045 in_flight = server->in_flight;
1046 spin_unlock(&server->req_lock);
1047 wake_up(&server->request_q);
1049 trace_smb3_add_credits(server->CurrentMid,
1050 server->conn_id, server->hostname, scredits,
1051 le16_to_cpu(shdr->CreditRequest), in_flight);
1052 cifs_server_dbg(FYI, "%s: added %u credits total=%d\n",
1053 __func__, le16_to_cpu(shdr->CreditRequest),
1060 cifs_demultiplex_thread(void *p)
1062 int i, num_mids, length;
1063 struct TCP_Server_Info *server = p;
1064 unsigned int pdu_length;
1065 unsigned int next_offset;
1067 struct task_struct *task_to_wake = NULL;
1068 struct mid_q_entry *mids[MAX_COMPOUND];
1069 char *bufs[MAX_COMPOUND];
1070 unsigned int noreclaim_flag, num_io_timeout = 0;
1072 noreclaim_flag = memalloc_noreclaim_save();
1073 cifs_dbg(FYI, "Demultiplex PID: %d\n", task_pid_nr(current));
1075 length = atomic_inc_return(&tcpSesAllocCount);
1077 mempool_resize(cifs_req_poolp, length + cifs_min_rcv);
1080 allow_kernel_signal(SIGKILL);
1081 while (server->tcpStatus != CifsExiting) {
1082 if (try_to_freeze())
1085 if (!allocate_buffers(server))
1088 server->large_buf = false;
1089 buf = server->smallbuf;
1090 pdu_length = 4; /* enough to get RFC1001 header */
1092 length = cifs_read_from_socket(server, buf, pdu_length);
1096 if (server->vals->header_preamble_size == 0)
1097 server->total_read = 0;
1099 server->total_read = length;
1102 * The right amount was read from socket - 4 bytes,
1103 * so we can now interpret the length field.
1105 pdu_length = get_rfc1002_length(buf);
1107 cifs_dbg(FYI, "RFC1002 header 0x%x\n", pdu_length);
1108 if (!is_smb_response(server, buf[0]))
1111 server->pdu_size = pdu_length;
1113 /* make sure we have enough to get to the MID */
1114 if (server->pdu_size < HEADER_SIZE(server) - 1 -
1115 server->vals->header_preamble_size) {
1116 cifs_server_dbg(VFS, "SMB response too short (%u bytes)\n",
1118 cifs_reconnect(server, true);
1122 /* read down to the MID */
1123 length = cifs_read_from_socket(server,
1124 buf + server->vals->header_preamble_size,
1125 HEADER_SIZE(server) - 1
1126 - server->vals->header_preamble_size);
1129 server->total_read += length;
1131 if (server->ops->next_header) {
1132 next_offset = server->ops->next_header(buf);
1134 server->pdu_size = next_offset;
1137 memset(mids, 0, sizeof(mids));
1138 memset(bufs, 0, sizeof(bufs));
1141 if (server->ops->is_transform_hdr &&
1142 server->ops->receive_transform &&
1143 server->ops->is_transform_hdr(buf)) {
1144 length = server->ops->receive_transform(server,
1149 mids[0] = server->ops->find_mid(server, buf);
1153 if (!mids[0] || !mids[0]->receive)
1154 length = standard_receive3(server, mids[0]);
1156 length = mids[0]->receive(server, mids[0]);
1160 for (i = 0; i < num_mids; i++)
1162 cifs_mid_q_entry_release(mids[i]);
1166 if (server->ops->is_status_io_timeout &&
1167 server->ops->is_status_io_timeout(buf)) {
1169 if (num_io_timeout > NUM_STATUS_IO_TIMEOUT) {
1170 cifs_reconnect(server, false);
1176 server->lstrp = jiffies;
1178 for (i = 0; i < num_mids; i++) {
1179 if (mids[i] != NULL) {
1180 mids[i]->resp_buf_size = server->pdu_size;
1182 if (bufs[i] && server->ops->is_network_name_deleted)
1183 server->ops->is_network_name_deleted(bufs[i],
1186 if (!mids[i]->multiRsp || mids[i]->multiEnd)
1187 mids[i]->callback(mids[i]);
1189 cifs_mid_q_entry_release(mids[i]);
1190 } else if (server->ops->is_oplock_break &&
1191 server->ops->is_oplock_break(bufs[i],
1193 smb2_add_credits_from_hdr(bufs[i], server);
1194 cifs_dbg(FYI, "Received oplock break\n");
1196 cifs_server_dbg(VFS, "No task to wake, unknown frame received! NumMids %d\n",
1197 atomic_read(&midCount));
1198 cifs_dump_mem("Received Data is: ", bufs[i],
1199 HEADER_SIZE(server));
1200 smb2_add_credits_from_hdr(bufs[i], server);
1201 #ifdef CONFIG_CIFS_DEBUG2
1202 if (server->ops->dump_detail)
1203 server->ops->dump_detail(bufs[i],
1205 cifs_dump_mids(server);
1206 #endif /* CIFS_DEBUG2 */
1210 if (pdu_length > server->pdu_size) {
1211 if (!allocate_buffers(server))
1213 pdu_length -= server->pdu_size;
1214 server->total_read = 0;
1215 server->large_buf = false;
1216 buf = server->smallbuf;
1219 } /* end while !EXITING */
1221 /* buffer usually freed in free_mid - need to free it here on exit */
1222 cifs_buf_release(server->bigbuf);
1223 if (server->smallbuf) /* no sense logging a debug message if NULL */
1224 cifs_small_buf_release(server->smallbuf);
1226 task_to_wake = xchg(&server->tsk, NULL);
1227 clean_demultiplex_info(server);
1229 /* if server->tsk was NULL then wait for a signal before exiting */
1230 if (!task_to_wake) {
1231 set_current_state(TASK_INTERRUPTIBLE);
1232 while (!signal_pending(current)) {
1234 set_current_state(TASK_INTERRUPTIBLE);
1236 set_current_state(TASK_RUNNING);
1239 memalloc_noreclaim_restore(noreclaim_flag);
1240 module_put_and_kthread_exit(0);
1244 * Returns true if srcaddr isn't specified and rhs isn't specified, or
1245 * if srcaddr is specified and matches the IP address of the rhs argument
1248 cifs_match_ipaddr(struct sockaddr *srcaddr, struct sockaddr *rhs)
1250 switch (srcaddr->sa_family) {
1252 return (rhs->sa_family == AF_UNSPEC);
1254 struct sockaddr_in *saddr4 = (struct sockaddr_in *)srcaddr;
1255 struct sockaddr_in *vaddr4 = (struct sockaddr_in *)rhs;
1256 return (saddr4->sin_addr.s_addr == vaddr4->sin_addr.s_addr);
1259 struct sockaddr_in6 *saddr6 = (struct sockaddr_in6 *)srcaddr;
1260 struct sockaddr_in6 *vaddr6 = (struct sockaddr_in6 *)rhs;
1261 return ipv6_addr_equal(&saddr6->sin6_addr, &vaddr6->sin6_addr);
1265 return false; /* don't expect to be here */
1270 * If no port is specified in addr structure, we try to match with 445 port
1271 * and if it fails - with 139 ports. It should be called only if address
1272 * families of server and addr are equal.
1275 match_port(struct TCP_Server_Info *server, struct sockaddr *addr)
1277 __be16 port, *sport;
1279 /* SMBDirect manages its own ports, don't match it here */
1283 switch (addr->sa_family) {
1285 sport = &((struct sockaddr_in *) &server->dstaddr)->sin_port;
1286 port = ((struct sockaddr_in *) addr)->sin_port;
1289 sport = &((struct sockaddr_in6 *) &server->dstaddr)->sin6_port;
1290 port = ((struct sockaddr_in6 *) addr)->sin6_port;
1298 port = htons(CIFS_PORT);
1302 port = htons(RFC1001_PORT);
1305 return port == *sport;
1309 match_address(struct TCP_Server_Info *server, struct sockaddr *addr,
1310 struct sockaddr *srcaddr)
1312 switch (addr->sa_family) {
1314 struct sockaddr_in *addr4 = (struct sockaddr_in *)addr;
1315 struct sockaddr_in *srv_addr4 =
1316 (struct sockaddr_in *)&server->dstaddr;
1318 if (addr4->sin_addr.s_addr != srv_addr4->sin_addr.s_addr)
1323 struct sockaddr_in6 *addr6 = (struct sockaddr_in6 *)addr;
1324 struct sockaddr_in6 *srv_addr6 =
1325 (struct sockaddr_in6 *)&server->dstaddr;
1327 if (!ipv6_addr_equal(&addr6->sin6_addr,
1328 &srv_addr6->sin6_addr))
1330 if (addr6->sin6_scope_id != srv_addr6->sin6_scope_id)
1336 return false; /* don't expect to be here */
1339 if (!cifs_match_ipaddr(srcaddr, (struct sockaddr *)&server->srcaddr))
1346 match_security(struct TCP_Server_Info *server, struct smb3_fs_context *ctx)
1349 * The select_sectype function should either return the ctx->sectype
1350 * that was specified, or "Unspecified" if that sectype was not
1351 * compatible with the given NEGOTIATE request.
1353 if (server->ops->select_sectype(server, ctx->sectype)
1358 * Now check if signing mode is acceptable. No need to check
1359 * global_secflags at this point since if MUST_SIGN is set then
1360 * the server->sign had better be too.
1362 if (ctx->sign && !server->sign)
1368 static int match_server(struct TCP_Server_Info *server, struct smb3_fs_context *ctx)
1370 struct sockaddr *addr = (struct sockaddr *)&ctx->dstaddr;
1372 if (ctx->nosharesock)
1375 /* this server does not share socket */
1376 if (server->nosharesock)
1379 /* If multidialect negotiation see if existing sessions match one */
1380 if (strcmp(ctx->vals->version_string, SMB3ANY_VERSION_STRING) == 0) {
1381 if (server->vals->protocol_id < SMB30_PROT_ID)
1383 } else if (strcmp(ctx->vals->version_string,
1384 SMBDEFAULT_VERSION_STRING) == 0) {
1385 if (server->vals->protocol_id < SMB21_PROT_ID)
1387 } else if ((server->vals != ctx->vals) || (server->ops != ctx->ops))
1390 if (!net_eq(cifs_net_ns(server), current->nsproxy->net_ns))
1393 if (strcasecmp(server->hostname, ctx->server_hostname))
1396 if (!match_address(server, addr,
1397 (struct sockaddr *)&ctx->srcaddr))
1400 if (!match_port(server, addr))
1403 if (!match_security(server, ctx))
1406 if (server->echo_interval != ctx->echo_interval * HZ)
1409 if (server->rdma != ctx->rdma)
1412 if (server->ignore_signature != ctx->ignore_signature)
1415 if (server->min_offload != ctx->min_offload)
1421 struct TCP_Server_Info *
1422 cifs_find_tcp_session(struct smb3_fs_context *ctx)
1424 struct TCP_Server_Info *server;
1426 spin_lock(&cifs_tcp_ses_lock);
1427 list_for_each_entry(server, &cifs_tcp_ses_list, tcp_ses_list) {
1428 #ifdef CONFIG_CIFS_DFS_UPCALL
1430 * DFS failover implementation in cifs_reconnect() requires unique tcp sessions for
1431 * DFS connections to do failover properly, so avoid sharing them with regular
1432 * shares or even links that may connect to same server but having completely
1433 * different failover targets.
1435 if (server->is_dfs_conn)
1439 * Skip ses channels since they're only handled in lower layers
1440 * (e.g. cifs_send_recv).
1442 if (CIFS_SERVER_IS_CHAN(server) || !match_server(server, ctx))
1445 ++server->srv_count;
1446 spin_unlock(&cifs_tcp_ses_lock);
1447 cifs_dbg(FYI, "Existing tcp session with server found\n");
1450 spin_unlock(&cifs_tcp_ses_lock);
1455 cifs_put_tcp_session(struct TCP_Server_Info *server, int from_reconnect)
1457 struct task_struct *task;
1459 spin_lock(&cifs_tcp_ses_lock);
1460 if (--server->srv_count > 0) {
1461 spin_unlock(&cifs_tcp_ses_lock);
1465 /* srv_count can never go negative */
1466 WARN_ON(server->srv_count < 0);
1468 put_net(cifs_net_ns(server));
1470 list_del_init(&server->tcp_ses_list);
1471 spin_unlock(&cifs_tcp_ses_lock);
1473 /* For secondary channels, we pick up ref-count on the primary server */
1474 if (CIFS_SERVER_IS_CHAN(server))
1475 cifs_put_tcp_session(server->primary_server, from_reconnect);
1477 cancel_delayed_work_sync(&server->echo);
1478 cancel_delayed_work_sync(&server->resolve);
1482 * Avoid deadlock here: reconnect work calls
1483 * cifs_put_tcp_session() at its end. Need to be sure
1484 * that reconnect work does nothing with server pointer after
1487 cancel_delayed_work(&server->reconnect);
1489 cancel_delayed_work_sync(&server->reconnect);
1491 spin_lock(&cifs_tcp_ses_lock);
1492 server->tcpStatus = CifsExiting;
1493 spin_unlock(&cifs_tcp_ses_lock);
1495 cifs_crypto_secmech_release(server);
1497 kfree(server->session_key.response);
1498 server->session_key.response = NULL;
1499 server->session_key.len = 0;
1500 kfree(server->hostname);
1502 task = xchg(&server->tsk, NULL);
1504 send_sig(SIGKILL, task, 1);
1507 struct TCP_Server_Info *
1508 cifs_get_tcp_session(struct smb3_fs_context *ctx,
1509 struct TCP_Server_Info *primary_server)
1511 struct TCP_Server_Info *tcp_ses = NULL;
1514 cifs_dbg(FYI, "UNC: %s\n", ctx->UNC);
1516 /* see if we already have a matching tcp_ses */
1517 tcp_ses = cifs_find_tcp_session(ctx);
1521 tcp_ses = kzalloc(sizeof(struct TCP_Server_Info), GFP_KERNEL);
1527 tcp_ses->hostname = kstrdup(ctx->server_hostname, GFP_KERNEL);
1528 if (!tcp_ses->hostname) {
1533 if (ctx->nosharesock)
1534 tcp_ses->nosharesock = true;
1536 tcp_ses->ops = ctx->ops;
1537 tcp_ses->vals = ctx->vals;
1538 cifs_set_net_ns(tcp_ses, get_net(current->nsproxy->net_ns));
1540 tcp_ses->conn_id = atomic_inc_return(&tcpSesNextId);
1541 tcp_ses->noblockcnt = ctx->rootfs;
1542 tcp_ses->noblocksnd = ctx->noblocksnd || ctx->rootfs;
1543 tcp_ses->noautotune = ctx->noautotune;
1544 tcp_ses->tcp_nodelay = ctx->sockopt_tcp_nodelay;
1545 tcp_ses->rdma = ctx->rdma;
1546 tcp_ses->in_flight = 0;
1547 tcp_ses->max_in_flight = 0;
1548 tcp_ses->credits = 1;
1549 if (primary_server) {
1550 spin_lock(&cifs_tcp_ses_lock);
1551 ++primary_server->srv_count;
1552 tcp_ses->primary_server = primary_server;
1553 spin_unlock(&cifs_tcp_ses_lock);
1555 init_waitqueue_head(&tcp_ses->response_q);
1556 init_waitqueue_head(&tcp_ses->request_q);
1557 INIT_LIST_HEAD(&tcp_ses->pending_mid_q);
1558 mutex_init(&tcp_ses->srv_mutex);
1559 memcpy(tcp_ses->workstation_RFC1001_name,
1560 ctx->source_rfc1001_name, RFC1001_NAME_LEN_WITH_NULL);
1561 memcpy(tcp_ses->server_RFC1001_name,
1562 ctx->target_rfc1001_name, RFC1001_NAME_LEN_WITH_NULL);
1563 tcp_ses->session_estab = false;
1564 tcp_ses->sequence_number = 0;
1565 tcp_ses->reconnect_instance = 1;
1566 tcp_ses->lstrp = jiffies;
1567 tcp_ses->compress_algorithm = cpu_to_le16(ctx->compression);
1568 spin_lock_init(&tcp_ses->req_lock);
1569 INIT_LIST_HEAD(&tcp_ses->tcp_ses_list);
1570 INIT_LIST_HEAD(&tcp_ses->smb_ses_list);
1571 INIT_DELAYED_WORK(&tcp_ses->echo, cifs_echo_request);
1572 INIT_DELAYED_WORK(&tcp_ses->resolve, cifs_resolve_server);
1573 INIT_DELAYED_WORK(&tcp_ses->reconnect, smb2_reconnect_server);
1574 mutex_init(&tcp_ses->reconnect_mutex);
1575 #ifdef CONFIG_CIFS_DFS_UPCALL
1576 mutex_init(&tcp_ses->refpath_lock);
1578 memcpy(&tcp_ses->srcaddr, &ctx->srcaddr,
1579 sizeof(tcp_ses->srcaddr));
1580 memcpy(&tcp_ses->dstaddr, &ctx->dstaddr,
1581 sizeof(tcp_ses->dstaddr));
1582 if (ctx->use_client_guid)
1583 memcpy(tcp_ses->client_guid, ctx->client_guid,
1584 SMB2_CLIENT_GUID_SIZE);
1586 generate_random_uuid(tcp_ses->client_guid);
1588 * at this point we are the only ones with the pointer
1589 * to the struct since the kernel thread not created yet
1590 * no need to spinlock this init of tcpStatus or srv_count
1592 tcp_ses->tcpStatus = CifsNew;
1593 ++tcp_ses->srv_count;
1595 if (ctx->echo_interval >= SMB_ECHO_INTERVAL_MIN &&
1596 ctx->echo_interval <= SMB_ECHO_INTERVAL_MAX)
1597 tcp_ses->echo_interval = ctx->echo_interval * HZ;
1599 tcp_ses->echo_interval = SMB_ECHO_INTERVAL_DEFAULT * HZ;
1600 if (tcp_ses->rdma) {
1601 #ifndef CONFIG_CIFS_SMB_DIRECT
1602 cifs_dbg(VFS, "CONFIG_CIFS_SMB_DIRECT is not enabled\n");
1604 goto out_err_crypto_release;
1606 tcp_ses->smbd_conn = smbd_get_connection(
1607 tcp_ses, (struct sockaddr *)&ctx->dstaddr);
1608 if (tcp_ses->smbd_conn) {
1609 cifs_dbg(VFS, "RDMA transport established\n");
1611 goto smbd_connected;
1614 goto out_err_crypto_release;
1617 rc = ip_connect(tcp_ses);
1619 cifs_dbg(VFS, "Error connecting to socket. Aborting operation.\n");
1620 goto out_err_crypto_release;
1624 * since we're in a cifs function already, we know that
1625 * this will succeed. No need for try_module_get().
1627 __module_get(THIS_MODULE);
1628 tcp_ses->tsk = kthread_run(cifs_demultiplex_thread,
1630 if (IS_ERR(tcp_ses->tsk)) {
1631 rc = PTR_ERR(tcp_ses->tsk);
1632 cifs_dbg(VFS, "error %d create cifsd thread\n", rc);
1633 module_put(THIS_MODULE);
1634 goto out_err_crypto_release;
1636 tcp_ses->min_offload = ctx->min_offload;
1638 * at this point we are the only ones with the pointer
1639 * to the struct since the kernel thread not created yet
1640 * no need to spinlock this update of tcpStatus
1642 spin_lock(&cifs_tcp_ses_lock);
1643 tcp_ses->tcpStatus = CifsNeedNegotiate;
1644 spin_unlock(&cifs_tcp_ses_lock);
1646 if ((ctx->max_credits < 20) || (ctx->max_credits > 60000))
1647 tcp_ses->max_credits = SMB2_MAX_CREDITS_AVAILABLE;
1649 tcp_ses->max_credits = ctx->max_credits;
1651 tcp_ses->nr_targets = 1;
1652 tcp_ses->ignore_signature = ctx->ignore_signature;
1653 /* thread spawned, put it on the list */
1654 spin_lock(&cifs_tcp_ses_lock);
1655 list_add(&tcp_ses->tcp_ses_list, &cifs_tcp_ses_list);
1656 spin_unlock(&cifs_tcp_ses_lock);
1658 /* queue echo request delayed work */
1659 queue_delayed_work(cifsiod_wq, &tcp_ses->echo, tcp_ses->echo_interval);
1661 /* queue dns resolution delayed work */
1662 cifs_dbg(FYI, "%s: next dns resolution scheduled for %d seconds in the future\n",
1663 __func__, SMB_DNS_RESOLVE_INTERVAL_DEFAULT);
1665 queue_delayed_work(cifsiod_wq, &tcp_ses->resolve, (SMB_DNS_RESOLVE_INTERVAL_DEFAULT * HZ));
1669 out_err_crypto_release:
1670 cifs_crypto_secmech_release(tcp_ses);
1672 put_net(cifs_net_ns(tcp_ses));
1676 if (CIFS_SERVER_IS_CHAN(tcp_ses))
1677 cifs_put_tcp_session(tcp_ses->primary_server, false);
1678 kfree(tcp_ses->hostname);
1679 if (tcp_ses->ssocket)
1680 sock_release(tcp_ses->ssocket);
1686 static int match_session(struct cifs_ses *ses, struct smb3_fs_context *ctx)
1688 if (ctx->sectype != Unspecified &&
1689 ctx->sectype != ses->sectype)
1693 * If an existing session is limited to less channels than
1694 * requested, it should not be reused
1696 spin_lock(&ses->chan_lock);
1697 if (ses->chan_max < ctx->max_channels) {
1698 spin_unlock(&ses->chan_lock);
1701 spin_unlock(&ses->chan_lock);
1703 switch (ses->sectype) {
1705 if (!uid_eq(ctx->cred_uid, ses->cred_uid))
1709 /* NULL username means anonymous session */
1710 if (ses->user_name == NULL) {
1716 /* anything else takes username/password */
1717 if (strncmp(ses->user_name,
1718 ctx->username ? ctx->username : "",
1719 CIFS_MAX_USERNAME_LEN))
1721 if ((ctx->username && strlen(ctx->username) != 0) &&
1722 ses->password != NULL &&
1723 strncmp(ses->password,
1724 ctx->password ? ctx->password : "",
1725 CIFS_MAX_PASSWORD_LEN))
1732 * cifs_setup_ipc - helper to setup the IPC tcon for the session
1733 * @ses: smb session to issue the request on
1734 * @ctx: the superblock configuration context to use for building the
1735 * new tree connection for the IPC (interprocess communication RPC)
1737 * A new IPC connection is made and stored in the session
1738 * tcon_ipc. The IPC tcon has the same lifetime as the session.
1741 cifs_setup_ipc(struct cifs_ses *ses, struct smb3_fs_context *ctx)
1744 struct cifs_tcon *tcon;
1745 char unc[SERVER_NAME_LENGTH + sizeof("//x/IPC$")] = {0};
1747 struct TCP_Server_Info *server = ses->server;
1750 * If the mount request that resulted in the creation of the
1751 * session requires encryption, force IPC to be encrypted too.
1754 if (server->capabilities & SMB2_GLOBAL_CAP_ENCRYPTION)
1757 cifs_server_dbg(VFS,
1758 "IPC: server doesn't support encryption\n");
1763 tcon = tconInfoAlloc();
1767 scnprintf(unc, sizeof(unc), "\\\\%s\\IPC$", server->hostname);
1773 rc = server->ops->tree_connect(xid, ses, unc, tcon, ctx->local_nls);
1777 cifs_server_dbg(VFS, "failed to connect to IPC (rc=%d)\n", rc);
1782 cifs_dbg(FYI, "IPC tcon rc = %d ipc tid = %d\n", rc, tcon->tid);
1784 ses->tcon_ipc = tcon;
1790 * cifs_free_ipc - helper to release the session IPC tcon
1791 * @ses: smb session to unmount the IPC from
1793 * Needs to be called everytime a session is destroyed.
1795 * On session close, the IPC is closed and the server must release all tcons of the session.
1796 * No need to send a tree disconnect here.
1798 * Besides, it will make the server to not close durable and resilient files on session close, as
1799 * specified in MS-SMB2 3.3.5.6 Receiving an SMB2 LOGOFF Request.
1802 cifs_free_ipc(struct cifs_ses *ses)
1804 struct cifs_tcon *tcon = ses->tcon_ipc;
1810 ses->tcon_ipc = NULL;
1814 static struct cifs_ses *
1815 cifs_find_smb_ses(struct TCP_Server_Info *server, struct smb3_fs_context *ctx)
1817 struct cifs_ses *ses;
1819 spin_lock(&cifs_tcp_ses_lock);
1820 list_for_each_entry(ses, &server->smb_ses_list, smb_ses_list) {
1821 if (ses->status == CifsExiting)
1823 if (!match_session(ses, ctx))
1826 spin_unlock(&cifs_tcp_ses_lock);
1829 spin_unlock(&cifs_tcp_ses_lock);
1833 void cifs_put_smb_ses(struct cifs_ses *ses)
1835 unsigned int rc, xid;
1836 unsigned int chan_count;
1837 struct TCP_Server_Info *server = ses->server;
1838 cifs_dbg(FYI, "%s: ses_count=%d\n", __func__, ses->ses_count);
1840 spin_lock(&cifs_tcp_ses_lock);
1841 if (ses->status == CifsExiting) {
1842 spin_unlock(&cifs_tcp_ses_lock);
1846 cifs_dbg(FYI, "%s: ses_count=%d\n", __func__, ses->ses_count);
1847 cifs_dbg(FYI, "%s: ses ipc: %s\n", __func__, ses->tcon_ipc ? ses->tcon_ipc->treeName : "NONE");
1849 if (--ses->ses_count > 0) {
1850 spin_unlock(&cifs_tcp_ses_lock);
1854 /* ses_count can never go negative */
1855 WARN_ON(ses->ses_count < 0);
1857 if (ses->status == CifsGood)
1858 ses->status = CifsExiting;
1859 spin_unlock(&cifs_tcp_ses_lock);
1863 if (ses->status == CifsExiting && server->ops->logoff) {
1865 rc = server->ops->logoff(xid, ses);
1867 cifs_server_dbg(VFS, "%s: Session Logoff failure rc=%d\n",
1872 spin_lock(&cifs_tcp_ses_lock);
1873 list_del_init(&ses->smb_ses_list);
1874 spin_unlock(&cifs_tcp_ses_lock);
1876 spin_lock(&ses->chan_lock);
1877 chan_count = ses->chan_count;
1879 /* close any extra channels */
1880 if (chan_count > 1) {
1883 for (i = 1; i < chan_count; i++) {
1884 spin_unlock(&ses->chan_lock);
1885 cifs_put_tcp_session(ses->chans[i].server, 0);
1886 spin_lock(&ses->chan_lock);
1887 ses->chans[i].server = NULL;
1890 spin_unlock(&ses->chan_lock);
1893 cifs_put_tcp_session(server, 0);
1898 /* strlen("cifs:a:") + CIFS_MAX_DOMAINNAME_LEN + 1 */
1899 #define CIFSCREDS_DESC_SIZE (7 + CIFS_MAX_DOMAINNAME_LEN + 1)
1901 /* Populate username and pw fields from keyring if possible */
1903 cifs_set_cifscreds(struct smb3_fs_context *ctx, struct cifs_ses *ses)
1907 const char *delim, *payload;
1911 struct TCP_Server_Info *server = ses->server;
1912 struct sockaddr_in *sa;
1913 struct sockaddr_in6 *sa6;
1914 const struct user_key_payload *upayload;
1916 desc = kmalloc(CIFSCREDS_DESC_SIZE, GFP_KERNEL);
1920 /* try to find an address key first */
1921 switch (server->dstaddr.ss_family) {
1923 sa = (struct sockaddr_in *)&server->dstaddr;
1924 sprintf(desc, "cifs:a:%pI4", &sa->sin_addr.s_addr);
1927 sa6 = (struct sockaddr_in6 *)&server->dstaddr;
1928 sprintf(desc, "cifs:a:%pI6c", &sa6->sin6_addr.s6_addr);
1931 cifs_dbg(FYI, "Bad ss_family (%hu)\n",
1932 server->dstaddr.ss_family);
1937 cifs_dbg(FYI, "%s: desc=%s\n", __func__, desc);
1938 key = request_key(&key_type_logon, desc, "");
1940 if (!ses->domainName) {
1941 cifs_dbg(FYI, "domainName is NULL\n");
1946 /* didn't work, try to find a domain key */
1947 sprintf(desc, "cifs:d:%s", ses->domainName);
1948 cifs_dbg(FYI, "%s: desc=%s\n", __func__, desc);
1949 key = request_key(&key_type_logon, desc, "");
1957 down_read(&key->sem);
1958 upayload = user_key_payload_locked(key);
1959 if (IS_ERR_OR_NULL(upayload)) {
1960 rc = upayload ? PTR_ERR(upayload) : -EINVAL;
1964 /* find first : in payload */
1965 payload = upayload->data;
1966 delim = strnchr(payload, upayload->datalen, ':');
1967 cifs_dbg(FYI, "payload=%s\n", payload);
1969 cifs_dbg(FYI, "Unable to find ':' in payload (datalen=%d)\n",
1975 len = delim - payload;
1976 if (len > CIFS_MAX_USERNAME_LEN || len <= 0) {
1977 cifs_dbg(FYI, "Bad value from username search (len=%zd)\n",
1983 ctx->username = kstrndup(payload, len, GFP_KERNEL);
1984 if (!ctx->username) {
1985 cifs_dbg(FYI, "Unable to allocate %zd bytes for username\n",
1990 cifs_dbg(FYI, "%s: username=%s\n", __func__, ctx->username);
1992 len = key->datalen - (len + 1);
1993 if (len > CIFS_MAX_PASSWORD_LEN || len <= 0) {
1994 cifs_dbg(FYI, "Bad len for password search (len=%zd)\n", len);
1996 kfree(ctx->username);
1997 ctx->username = NULL;
2002 ctx->password = kstrndup(delim, len, GFP_KERNEL);
2003 if (!ctx->password) {
2004 cifs_dbg(FYI, "Unable to allocate %zd bytes for password\n",
2007 kfree(ctx->username);
2008 ctx->username = NULL;
2013 * If we have a domain key then we must set the domainName in the
2016 if (is_domain && ses->domainName) {
2017 ctx->domainname = kstrdup(ses->domainName, GFP_KERNEL);
2018 if (!ctx->domainname) {
2019 cifs_dbg(FYI, "Unable to allocate %zd bytes for domain\n",
2022 kfree(ctx->username);
2023 ctx->username = NULL;
2024 kfree_sensitive(ctx->password);
2025 ctx->password = NULL;
2030 ctx->workstation_name = kstrdup(ses->workstation_name, GFP_KERNEL);
2031 if (!ctx->workstation_name) {
2032 cifs_dbg(FYI, "Unable to allocate memory for workstation_name\n");
2034 kfree(ctx->username);
2035 ctx->username = NULL;
2036 kfree_sensitive(ctx->password);
2037 ctx->password = NULL;
2038 kfree(ctx->domainname);
2039 ctx->domainname = NULL;
2048 cifs_dbg(FYI, "%s: returning %d\n", __func__, rc);
2051 #else /* ! CONFIG_KEYS */
2053 cifs_set_cifscreds(struct smb3_fs_context *ctx __attribute__((unused)),
2054 struct cifs_ses *ses __attribute__((unused)))
2058 #endif /* CONFIG_KEYS */
2061 * cifs_get_smb_ses - get a session matching @ctx data from @server
2062 * @server: server to setup the session to
2063 * @ctx: superblock configuration context to use to setup the session
2065 * This function assumes it is being called from cifs_mount() where we
2066 * already got a server reference (server refcount +1). See
2067 * cifs_get_tcon() for refcount explanations.
2070 cifs_get_smb_ses(struct TCP_Server_Info *server, struct smb3_fs_context *ctx)
2074 struct cifs_ses *ses;
2075 struct sockaddr_in *addr = (struct sockaddr_in *)&server->dstaddr;
2076 struct sockaddr_in6 *addr6 = (struct sockaddr_in6 *)&server->dstaddr;
2080 ses = cifs_find_smb_ses(server, ctx);
2082 cifs_dbg(FYI, "Existing smb sess found (status=%d)\n",
2085 spin_lock(&ses->chan_lock);
2086 if (cifs_chan_needs_reconnect(ses, server)) {
2087 spin_unlock(&ses->chan_lock);
2088 cifs_dbg(FYI, "Session needs reconnect\n");
2090 mutex_lock(&ses->session_mutex);
2091 rc = cifs_negotiate_protocol(xid, ses, server);
2093 mutex_unlock(&ses->session_mutex);
2094 /* problem -- put our ses reference */
2095 cifs_put_smb_ses(ses);
2100 rc = cifs_setup_session(xid, ses, server,
2103 mutex_unlock(&ses->session_mutex);
2104 /* problem -- put our reference */
2105 cifs_put_smb_ses(ses);
2109 mutex_unlock(&ses->session_mutex);
2111 spin_lock(&ses->chan_lock);
2113 spin_unlock(&ses->chan_lock);
2115 /* existing SMB ses has a server reference already */
2116 cifs_put_tcp_session(server, 0);
2121 cifs_dbg(FYI, "Existing smb sess not found\n");
2122 ses = sesInfoAlloc();
2126 /* new SMB session uses our server ref */
2127 ses->server = server;
2128 if (server->dstaddr.ss_family == AF_INET6)
2129 sprintf(ses->ip_addr, "%pI6", &addr6->sin6_addr);
2131 sprintf(ses->ip_addr, "%pI4", &addr->sin_addr);
2133 if (ctx->username) {
2134 ses->user_name = kstrdup(ctx->username, GFP_KERNEL);
2135 if (!ses->user_name)
2139 /* ctx->password freed at unmount */
2140 if (ctx->password) {
2141 ses->password = kstrdup(ctx->password, GFP_KERNEL);
2145 if (ctx->domainname) {
2146 ses->domainName = kstrdup(ctx->domainname, GFP_KERNEL);
2147 if (!ses->domainName)
2150 if (ctx->workstation_name) {
2151 ses->workstation_name = kstrdup(ctx->workstation_name,
2153 if (!ses->workstation_name)
2156 if (ctx->domainauto)
2157 ses->domainAuto = ctx->domainauto;
2158 ses->cred_uid = ctx->cred_uid;
2159 ses->linux_uid = ctx->linux_uid;
2161 ses->sectype = ctx->sectype;
2162 ses->sign = ctx->sign;
2164 /* add server as first channel */
2165 spin_lock(&ses->chan_lock);
2166 ses->chans[0].server = server;
2167 ses->chan_count = 1;
2168 ses->chan_max = ctx->multichannel ? ctx->max_channels:1;
2169 ses->chans_need_reconnect = 1;
2170 spin_unlock(&ses->chan_lock);
2172 mutex_lock(&ses->session_mutex);
2173 rc = cifs_negotiate_protocol(xid, ses, server);
2175 rc = cifs_setup_session(xid, ses, server, ctx->local_nls);
2176 mutex_unlock(&ses->session_mutex);
2178 /* each channel uses a different signing key */
2179 spin_lock(&ses->chan_lock);
2180 memcpy(ses->chans[0].signkey, ses->smb3signingkey,
2181 sizeof(ses->smb3signingkey));
2182 spin_unlock(&ses->chan_lock);
2188 * success, put it on the list and add it as first channel
2189 * note: the session becomes active soon after this. So you'll
2190 * need to lock before changing something in the session.
2192 spin_lock(&cifs_tcp_ses_lock);
2193 list_add(&ses->smb_ses_list, &server->smb_ses_list);
2194 spin_unlock(&cifs_tcp_ses_lock);
2198 cifs_setup_ipc(ses, ctx);
2208 static int match_tcon(struct cifs_tcon *tcon, struct smb3_fs_context *ctx)
2210 if (tcon->status == TID_EXITING)
2212 if (strncmp(tcon->treeName, ctx->UNC, MAX_TREE_SIZE))
2214 if (tcon->seal != ctx->seal)
2216 if (tcon->snapshot_time != ctx->snapshot_time)
2218 if (tcon->handle_timeout != ctx->handle_timeout)
2220 if (tcon->no_lease != ctx->no_lease)
2222 if (tcon->nodelete != ctx->nodelete)
2227 static struct cifs_tcon *
2228 cifs_find_tcon(struct cifs_ses *ses, struct smb3_fs_context *ctx)
2230 struct list_head *tmp;
2231 struct cifs_tcon *tcon;
2233 spin_lock(&cifs_tcp_ses_lock);
2234 list_for_each(tmp, &ses->tcon_list) {
2235 tcon = list_entry(tmp, struct cifs_tcon, tcon_list);
2237 if (!match_tcon(tcon, ctx))
2240 spin_unlock(&cifs_tcp_ses_lock);
2243 spin_unlock(&cifs_tcp_ses_lock);
2248 cifs_put_tcon(struct cifs_tcon *tcon)
2251 struct cifs_ses *ses;
2254 * IPC tcon share the lifetime of their session and are
2255 * destroyed in the session put function
2257 if (tcon == NULL || tcon->ipc)
2261 cifs_dbg(FYI, "%s: tc_count=%d\n", __func__, tcon->tc_count);
2262 spin_lock(&cifs_tcp_ses_lock);
2263 if (--tcon->tc_count > 0) {
2264 spin_unlock(&cifs_tcp_ses_lock);
2268 /* tc_count can never go negative */
2269 WARN_ON(tcon->tc_count < 0);
2271 list_del_init(&tcon->tcon_list);
2272 spin_unlock(&cifs_tcp_ses_lock);
2274 if (tcon->use_witness) {
2277 rc = cifs_swn_unregister(tcon);
2279 cifs_dbg(VFS, "%s: Failed to unregister for witness notifications: %d\n",
2285 if (ses->server->ops->tree_disconnect)
2286 ses->server->ops->tree_disconnect(xid, tcon);
2289 cifs_fscache_release_super_cookie(tcon);
2291 cifs_put_smb_ses(ses);
2295 * cifs_get_tcon - get a tcon matching @ctx data from @ses
2296 * @ses: smb session to issue the request on
2297 * @ctx: the superblock configuration context to use for building the
2299 * - tcon refcount is the number of mount points using the tcon.
2300 * - ses refcount is the number of tcon using the session.
2302 * 1. This function assumes it is being called from cifs_mount() where
2303 * we already got a session reference (ses refcount +1).
2305 * 2. Since we're in the context of adding a mount point, the end
2306 * result should be either:
2308 * a) a new tcon already allocated with refcount=1 (1 mount point) and
2309 * its session refcount incremented (1 new tcon). This +1 was
2310 * already done in (1).
2312 * b) an existing tcon with refcount+1 (add a mount point to it) and
2313 * identical ses refcount (no new tcon). Because of (1) we need to
2314 * decrement the ses refcount.
2316 static struct cifs_tcon *
2317 cifs_get_tcon(struct cifs_ses *ses, struct smb3_fs_context *ctx)
2320 struct cifs_tcon *tcon;
2322 tcon = cifs_find_tcon(ses, ctx);
2325 * tcon has refcount already incremented but we need to
2326 * decrement extra ses reference gotten by caller (case b)
2328 cifs_dbg(FYI, "Found match on UNC path\n");
2329 cifs_put_smb_ses(ses);
2333 if (!ses->server->ops->tree_connect) {
2338 tcon = tconInfoAlloc();
2344 if (ctx->snapshot_time) {
2345 if (ses->server->vals->protocol_id == 0) {
2347 "Use SMB2 or later for snapshot mount option\n");
2351 tcon->snapshot_time = ctx->snapshot_time;
2354 if (ctx->handle_timeout) {
2355 if (ses->server->vals->protocol_id == 0) {
2357 "Use SMB2.1 or later for handle timeout option\n");
2361 tcon->handle_timeout = ctx->handle_timeout;
2365 if (ctx->password) {
2366 tcon->password = kstrdup(ctx->password, GFP_KERNEL);
2367 if (!tcon->password) {
2374 if (ses->server->vals->protocol_id == 0) {
2376 "SMB3 or later required for encryption\n");
2379 } else if (tcon->ses->server->capabilities &
2380 SMB2_GLOBAL_CAP_ENCRYPTION)
2383 cifs_dbg(VFS, "Encryption is not supported on share\n");
2389 if (ctx->linux_ext) {
2390 if (ses->server->posix_ext_supported) {
2391 tcon->posix_extensions = true;
2392 pr_warn_once("SMB3.11 POSIX Extensions are experimental\n");
2393 } else if ((ses->server->vals->protocol_id == SMB311_PROT_ID) ||
2394 (strcmp(ses->server->vals->version_string,
2395 SMB3ANY_VERSION_STRING) == 0) ||
2396 (strcmp(ses->server->vals->version_string,
2397 SMBDEFAULT_VERSION_STRING) == 0)) {
2398 cifs_dbg(VFS, "Server does not support mounting with posix SMB3.11 extensions\n");
2402 cifs_dbg(VFS, "Check vers= mount option. SMB3.11 "
2403 "disabled but required for POSIX extensions\n");
2410 rc = ses->server->ops->tree_connect(xid, ses, ctx->UNC, tcon,
2413 cifs_dbg(FYI, "Tcon rc = %d\n", rc);
2417 tcon->use_persistent = false;
2418 /* check if SMB2 or later, CIFS does not support persistent handles */
2419 if (ctx->persistent) {
2420 if (ses->server->vals->protocol_id == 0) {
2422 "SMB3 or later required for persistent handles\n");
2425 } else if (ses->server->capabilities &
2426 SMB2_GLOBAL_CAP_PERSISTENT_HANDLES)
2427 tcon->use_persistent = true;
2428 else /* persistent handles requested but not supported */ {
2430 "Persistent handles not supported on share\n");
2434 } else if ((tcon->capabilities & SMB2_SHARE_CAP_CONTINUOUS_AVAILABILITY)
2435 && (ses->server->capabilities & SMB2_GLOBAL_CAP_PERSISTENT_HANDLES)
2436 && (ctx->nopersistent == false)) {
2437 cifs_dbg(FYI, "enabling persistent handles\n");
2438 tcon->use_persistent = true;
2439 } else if (ctx->resilient) {
2440 if (ses->server->vals->protocol_id == 0) {
2442 "SMB2.1 or later required for resilient handles\n");
2446 tcon->use_resilient = true;
2449 tcon->use_witness = false;
2450 if (IS_ENABLED(CONFIG_CIFS_SWN_UPCALL) && ctx->witness) {
2451 if (ses->server->vals->protocol_id >= SMB30_PROT_ID) {
2452 if (tcon->capabilities & SMB2_SHARE_CAP_CLUSTER) {
2454 * Set witness in use flag in first place
2455 * to retry registration in the echo task
2457 tcon->use_witness = true;
2458 /* And try to register immediately */
2459 rc = cifs_swn_register(tcon);
2461 cifs_dbg(VFS, "Failed to register for witness notifications: %d\n", rc);
2465 /* TODO: try to extend for non-cluster uses (eg multichannel) */
2466 cifs_dbg(VFS, "witness requested on mount but no CLUSTER capability on share\n");
2471 cifs_dbg(VFS, "SMB3 or later required for witness option\n");
2477 /* If the user really knows what they are doing they can override */
2478 if (tcon->share_flags & SMB2_SHAREFLAG_NO_CACHING) {
2480 cifs_dbg(VFS, "cache=ro requested on mount but NO_CACHING flag set on share\n");
2481 else if (ctx->cache_rw)
2482 cifs_dbg(VFS, "cache=singleclient requested on mount but NO_CACHING flag set on share\n");
2485 if (ctx->no_lease) {
2486 if (ses->server->vals->protocol_id == 0) {
2488 "SMB2 or later required for nolease option\n");
2492 tcon->no_lease = ctx->no_lease;
2496 * We can have only one retry value for a connection to a share so for
2497 * resources mounted more than once to the same server share the last
2498 * value passed in for the retry flag is used.
2500 tcon->retry = ctx->retry;
2501 tcon->nocase = ctx->nocase;
2502 if (ses->server->capabilities & SMB2_GLOBAL_CAP_DIRECTORY_LEASING)
2503 tcon->nohandlecache = ctx->nohandlecache;
2505 tcon->nohandlecache = true;
2506 tcon->nodelete = ctx->nodelete;
2507 tcon->local_lease = ctx->local_lease;
2508 INIT_LIST_HEAD(&tcon->pending_opens);
2510 spin_lock(&cifs_tcp_ses_lock);
2511 list_add(&tcon->tcon_list, &ses->tcon_list);
2512 spin_unlock(&cifs_tcp_ses_lock);
2522 cifs_put_tlink(struct tcon_link *tlink)
2524 if (!tlink || IS_ERR(tlink))
2527 if (!atomic_dec_and_test(&tlink->tl_count) ||
2528 test_bit(TCON_LINK_IN_TREE, &tlink->tl_flags)) {
2529 tlink->tl_time = jiffies;
2533 if (!IS_ERR(tlink_tcon(tlink)))
2534 cifs_put_tcon(tlink_tcon(tlink));
2540 compare_mount_options(struct super_block *sb, struct cifs_mnt_data *mnt_data)
2542 struct cifs_sb_info *old = CIFS_SB(sb);
2543 struct cifs_sb_info *new = mnt_data->cifs_sb;
2544 unsigned int oldflags = old->mnt_cifs_flags & CIFS_MOUNT_MASK;
2545 unsigned int newflags = new->mnt_cifs_flags & CIFS_MOUNT_MASK;
2547 if ((sb->s_flags & CIFS_MS_MASK) != (mnt_data->flags & CIFS_MS_MASK))
2550 if (old->mnt_cifs_serverino_autodisabled)
2551 newflags &= ~CIFS_MOUNT_SERVER_INUM;
2553 if (oldflags != newflags)
2557 * We want to share sb only if we don't specify an r/wsize or
2558 * specified r/wsize is greater than or equal to existing one.
2560 if (new->ctx->wsize && new->ctx->wsize < old->ctx->wsize)
2563 if (new->ctx->rsize && new->ctx->rsize < old->ctx->rsize)
2566 if (!uid_eq(old->ctx->linux_uid, new->ctx->linux_uid) ||
2567 !gid_eq(old->ctx->linux_gid, new->ctx->linux_gid))
2570 if (old->ctx->file_mode != new->ctx->file_mode ||
2571 old->ctx->dir_mode != new->ctx->dir_mode)
2574 if (strcmp(old->local_nls->charset, new->local_nls->charset))
2577 if (old->ctx->acregmax != new->ctx->acregmax)
2579 if (old->ctx->acdirmax != new->ctx->acdirmax)
2586 match_prepath(struct super_block *sb, struct cifs_mnt_data *mnt_data)
2588 struct cifs_sb_info *old = CIFS_SB(sb);
2589 struct cifs_sb_info *new = mnt_data->cifs_sb;
2590 bool old_set = (old->mnt_cifs_flags & CIFS_MOUNT_USE_PREFIX_PATH) &&
2592 bool new_set = (new->mnt_cifs_flags & CIFS_MOUNT_USE_PREFIX_PATH) &&
2595 if (old_set && new_set && !strcmp(new->prepath, old->prepath))
2597 else if (!old_set && !new_set)
2604 cifs_match_super(struct super_block *sb, void *data)
2606 struct cifs_mnt_data *mnt_data = (struct cifs_mnt_data *)data;
2607 struct smb3_fs_context *ctx;
2608 struct cifs_sb_info *cifs_sb;
2609 struct TCP_Server_Info *tcp_srv;
2610 struct cifs_ses *ses;
2611 struct cifs_tcon *tcon;
2612 struct tcon_link *tlink;
2615 spin_lock(&cifs_tcp_ses_lock);
2616 cifs_sb = CIFS_SB(sb);
2617 tlink = cifs_get_tlink(cifs_sb_master_tlink(cifs_sb));
2618 if (tlink == NULL) {
2619 /* can not match superblock if tlink were ever null */
2620 spin_unlock(&cifs_tcp_ses_lock);
2623 tcon = tlink_tcon(tlink);
2625 tcp_srv = ses->server;
2627 ctx = mnt_data->ctx;
2629 if (!match_server(tcp_srv, ctx) ||
2630 !match_session(ses, ctx) ||
2631 !match_tcon(tcon, ctx) ||
2632 !match_prepath(sb, mnt_data)) {
2637 rc = compare_mount_options(sb, mnt_data);
2639 spin_unlock(&cifs_tcp_ses_lock);
2640 cifs_put_tlink(tlink);
2644 #ifdef CONFIG_DEBUG_LOCK_ALLOC
2645 static struct lock_class_key cifs_key[2];
2646 static struct lock_class_key cifs_slock_key[2];
2649 cifs_reclassify_socket4(struct socket *sock)
2651 struct sock *sk = sock->sk;
2652 BUG_ON(!sock_allow_reclassification(sk));
2653 sock_lock_init_class_and_name(sk, "slock-AF_INET-CIFS",
2654 &cifs_slock_key[0], "sk_lock-AF_INET-CIFS", &cifs_key[0]);
2658 cifs_reclassify_socket6(struct socket *sock)
2660 struct sock *sk = sock->sk;
2661 BUG_ON(!sock_allow_reclassification(sk));
2662 sock_lock_init_class_and_name(sk, "slock-AF_INET6-CIFS",
2663 &cifs_slock_key[1], "sk_lock-AF_INET6-CIFS", &cifs_key[1]);
2667 cifs_reclassify_socket4(struct socket *sock)
2672 cifs_reclassify_socket6(struct socket *sock)
2677 /* See RFC1001 section 14 on representation of Netbios names */
2678 static void rfc1002mangle(char *target, char *source, unsigned int length)
2682 for (i = 0, j = 0; i < (length); i++) {
2683 /* mask a nibble at a time and encode */
2684 target[j] = 'A' + (0x0F & (source[i] >> 4));
2685 target[j+1] = 'A' + (0x0F & source[i]);
2692 bind_socket(struct TCP_Server_Info *server)
2695 if (server->srcaddr.ss_family != AF_UNSPEC) {
2696 /* Bind to the specified local IP address */
2697 struct socket *socket = server->ssocket;
2698 rc = socket->ops->bind(socket,
2699 (struct sockaddr *) &server->srcaddr,
2700 sizeof(server->srcaddr));
2702 struct sockaddr_in *saddr4;
2703 struct sockaddr_in6 *saddr6;
2704 saddr4 = (struct sockaddr_in *)&server->srcaddr;
2705 saddr6 = (struct sockaddr_in6 *)&server->srcaddr;
2706 if (saddr6->sin6_family == AF_INET6)
2707 cifs_server_dbg(VFS, "Failed to bind to: %pI6c, error: %d\n",
2708 &saddr6->sin6_addr, rc);
2710 cifs_server_dbg(VFS, "Failed to bind to: %pI4, error: %d\n",
2711 &saddr4->sin_addr.s_addr, rc);
2718 ip_rfc1001_connect(struct TCP_Server_Info *server)
2722 * some servers require RFC1001 sessinit before sending
2723 * negprot - BB check reconnection in case where second
2724 * sessinit is sent but no second negprot
2726 struct rfc1002_session_packet *ses_init_buf;
2727 struct smb_hdr *smb_buf;
2728 ses_init_buf = kzalloc(sizeof(struct rfc1002_session_packet),
2731 ses_init_buf->trailer.session_req.called_len = 32;
2733 if (server->server_RFC1001_name[0] != 0)
2734 rfc1002mangle(ses_init_buf->trailer.
2735 session_req.called_name,
2736 server->server_RFC1001_name,
2737 RFC1001_NAME_LEN_WITH_NULL);
2739 rfc1002mangle(ses_init_buf->trailer.
2740 session_req.called_name,
2741 DEFAULT_CIFS_CALLED_NAME,
2742 RFC1001_NAME_LEN_WITH_NULL);
2744 ses_init_buf->trailer.session_req.calling_len = 32;
2747 * calling name ends in null (byte 16) from old smb
2750 if (server->workstation_RFC1001_name[0] != 0)
2751 rfc1002mangle(ses_init_buf->trailer.
2752 session_req.calling_name,
2753 server->workstation_RFC1001_name,
2754 RFC1001_NAME_LEN_WITH_NULL);
2756 rfc1002mangle(ses_init_buf->trailer.
2757 session_req.calling_name,
2759 RFC1001_NAME_LEN_WITH_NULL);
2761 ses_init_buf->trailer.session_req.scope1 = 0;
2762 ses_init_buf->trailer.session_req.scope2 = 0;
2763 smb_buf = (struct smb_hdr *)ses_init_buf;
2765 /* sizeof RFC1002_SESSION_REQUEST with no scope */
2766 smb_buf->smb_buf_length = cpu_to_be32(0x81000044);
2767 rc = smb_send(server, smb_buf, 0x44);
2768 kfree(ses_init_buf);
2770 * RFC1001 layer in at least one server
2771 * requires very short break before negprot
2772 * presumably because not expecting negprot
2773 * to follow so fast. This is a simple
2774 * solution that works without
2775 * complicating the code and causes no
2776 * significant slowing down on mount
2779 usleep_range(1000, 2000);
2782 * else the negprot may still work without this
2783 * even though malloc failed
2790 generic_ip_connect(struct TCP_Server_Info *server)
2795 struct socket *socket = server->ssocket;
2796 struct sockaddr *saddr;
2798 saddr = (struct sockaddr *) &server->dstaddr;
2800 if (server->dstaddr.ss_family == AF_INET6) {
2801 struct sockaddr_in6 *ipv6 = (struct sockaddr_in6 *)&server->dstaddr;
2803 sport = ipv6->sin6_port;
2804 slen = sizeof(struct sockaddr_in6);
2806 cifs_dbg(FYI, "%s: connecting to [%pI6]:%d\n", __func__, &ipv6->sin6_addr,
2809 struct sockaddr_in *ipv4 = (struct sockaddr_in *)&server->dstaddr;
2811 sport = ipv4->sin_port;
2812 slen = sizeof(struct sockaddr_in);
2814 cifs_dbg(FYI, "%s: connecting to %pI4:%d\n", __func__, &ipv4->sin_addr,
2818 if (socket == NULL) {
2819 rc = __sock_create(cifs_net_ns(server), sfamily, SOCK_STREAM,
2820 IPPROTO_TCP, &socket, 1);
2822 cifs_server_dbg(VFS, "Error %d creating socket\n", rc);
2823 server->ssocket = NULL;
2827 /* BB other socket options to set KEEPALIVE, NODELAY? */
2828 cifs_dbg(FYI, "Socket created\n");
2829 server->ssocket = socket;
2830 socket->sk->sk_allocation = GFP_NOFS;
2831 if (sfamily == AF_INET6)
2832 cifs_reclassify_socket6(socket);
2834 cifs_reclassify_socket4(socket);
2837 rc = bind_socket(server);
2842 * Eventually check for other socket options to change from
2843 * the default. sock_setsockopt not used because it expects
2846 socket->sk->sk_rcvtimeo = 7 * HZ;
2847 socket->sk->sk_sndtimeo = 5 * HZ;
2849 /* make the bufsizes depend on wsize/rsize and max requests */
2850 if (server->noautotune) {
2851 if (socket->sk->sk_sndbuf < (200 * 1024))
2852 socket->sk->sk_sndbuf = 200 * 1024;
2853 if (socket->sk->sk_rcvbuf < (140 * 1024))
2854 socket->sk->sk_rcvbuf = 140 * 1024;
2857 if (server->tcp_nodelay)
2858 tcp_sock_set_nodelay(socket->sk);
2860 cifs_dbg(FYI, "sndbuf %d rcvbuf %d rcvtimeo 0x%lx\n",
2861 socket->sk->sk_sndbuf,
2862 socket->sk->sk_rcvbuf, socket->sk->sk_rcvtimeo);
2864 rc = socket->ops->connect(socket, saddr, slen,
2865 server->noblockcnt ? O_NONBLOCK : 0);
2867 * When mounting SMB root file systems, we do not want to block in
2868 * connect. Otherwise bail out and then let cifs_reconnect() perform
2869 * reconnect failover - if possible.
2871 if (server->noblockcnt && rc == -EINPROGRESS)
2874 cifs_dbg(FYI, "Error %d connecting to server\n", rc);
2875 trace_smb3_connect_err(server->hostname, server->conn_id, &server->dstaddr, rc);
2876 sock_release(socket);
2877 server->ssocket = NULL;
2880 trace_smb3_connect_done(server->hostname, server->conn_id, &server->dstaddr);
2881 if (sport == htons(RFC1001_PORT))
2882 rc = ip_rfc1001_connect(server);
2888 ip_connect(struct TCP_Server_Info *server)
2891 struct sockaddr_in6 *addr6 = (struct sockaddr_in6 *)&server->dstaddr;
2892 struct sockaddr_in *addr = (struct sockaddr_in *)&server->dstaddr;
2894 if (server->dstaddr.ss_family == AF_INET6)
2895 sport = &addr6->sin6_port;
2897 sport = &addr->sin_port;
2902 /* try with 445 port at first */
2903 *sport = htons(CIFS_PORT);
2905 rc = generic_ip_connect(server);
2909 /* if it failed, try with 139 port */
2910 *sport = htons(RFC1001_PORT);
2913 return generic_ip_connect(server);
2916 void reset_cifs_unix_caps(unsigned int xid, struct cifs_tcon *tcon,
2917 struct cifs_sb_info *cifs_sb, struct smb3_fs_context *ctx)
2920 * If we are reconnecting then should we check to see if
2921 * any requested capabilities changed locally e.g. via
2922 * remount but we can not do much about it here
2923 * if they have (even if we could detect it by the following)
2924 * Perhaps we could add a backpointer to array of sb from tcon
2925 * or if we change to make all sb to same share the same
2926 * sb as NFS - then we only have one backpointer to sb.
2927 * What if we wanted to mount the server share twice once with
2928 * and once without posixacls or posix paths?
2930 __u64 saved_cap = le64_to_cpu(tcon->fsUnixInfo.Capability);
2932 if (ctx && ctx->no_linux_ext) {
2933 tcon->fsUnixInfo.Capability = 0;
2934 tcon->unix_ext = 0; /* Unix Extensions disabled */
2935 cifs_dbg(FYI, "Linux protocol extensions disabled\n");
2938 tcon->unix_ext = 1; /* Unix Extensions supported */
2940 if (!tcon->unix_ext) {
2941 cifs_dbg(FYI, "Unix extensions disabled so not set on reconnect\n");
2945 if (!CIFSSMBQFSUnixInfo(xid, tcon)) {
2946 __u64 cap = le64_to_cpu(tcon->fsUnixInfo.Capability);
2947 cifs_dbg(FYI, "unix caps which server supports %lld\n", cap);
2949 * check for reconnect case in which we do not
2950 * want to change the mount behavior if we can avoid it
2954 * turn off POSIX ACL and PATHNAMES if not set
2955 * originally at mount time
2957 if ((saved_cap & CIFS_UNIX_POSIX_ACL_CAP) == 0)
2958 cap &= ~CIFS_UNIX_POSIX_ACL_CAP;
2959 if ((saved_cap & CIFS_UNIX_POSIX_PATHNAMES_CAP) == 0) {
2960 if (cap & CIFS_UNIX_POSIX_PATHNAMES_CAP)
2961 cifs_dbg(VFS, "POSIXPATH support change\n");
2962 cap &= ~CIFS_UNIX_POSIX_PATHNAMES_CAP;
2963 } else if ((cap & CIFS_UNIX_POSIX_PATHNAMES_CAP) == 0) {
2964 cifs_dbg(VFS, "possible reconnect error\n");
2965 cifs_dbg(VFS, "server disabled POSIX path support\n");
2969 if (cap & CIFS_UNIX_TRANSPORT_ENCRYPTION_MANDATORY_CAP)
2970 cifs_dbg(VFS, "per-share encryption not supported yet\n");
2972 cap &= CIFS_UNIX_CAP_MASK;
2973 if (ctx && ctx->no_psx_acl)
2974 cap &= ~CIFS_UNIX_POSIX_ACL_CAP;
2975 else if (CIFS_UNIX_POSIX_ACL_CAP & cap) {
2976 cifs_dbg(FYI, "negotiated posix acl support\n");
2978 cifs_sb->mnt_cifs_flags |=
2979 CIFS_MOUNT_POSIXACL;
2982 if (ctx && ctx->posix_paths == 0)
2983 cap &= ~CIFS_UNIX_POSIX_PATHNAMES_CAP;
2984 else if (cap & CIFS_UNIX_POSIX_PATHNAMES_CAP) {
2985 cifs_dbg(FYI, "negotiate posix pathnames\n");
2987 cifs_sb->mnt_cifs_flags |=
2988 CIFS_MOUNT_POSIX_PATHS;
2991 cifs_dbg(FYI, "Negotiate caps 0x%x\n", (int)cap);
2992 #ifdef CONFIG_CIFS_DEBUG2
2993 if (cap & CIFS_UNIX_FCNTL_CAP)
2994 cifs_dbg(FYI, "FCNTL cap\n");
2995 if (cap & CIFS_UNIX_EXTATTR_CAP)
2996 cifs_dbg(FYI, "EXTATTR cap\n");
2997 if (cap & CIFS_UNIX_POSIX_PATHNAMES_CAP)
2998 cifs_dbg(FYI, "POSIX path cap\n");
2999 if (cap & CIFS_UNIX_XATTR_CAP)
3000 cifs_dbg(FYI, "XATTR cap\n");
3001 if (cap & CIFS_UNIX_POSIX_ACL_CAP)
3002 cifs_dbg(FYI, "POSIX ACL cap\n");
3003 if (cap & CIFS_UNIX_LARGE_READ_CAP)
3004 cifs_dbg(FYI, "very large read cap\n");
3005 if (cap & CIFS_UNIX_LARGE_WRITE_CAP)
3006 cifs_dbg(FYI, "very large write cap\n");
3007 if (cap & CIFS_UNIX_TRANSPORT_ENCRYPTION_CAP)
3008 cifs_dbg(FYI, "transport encryption cap\n");
3009 if (cap & CIFS_UNIX_TRANSPORT_ENCRYPTION_MANDATORY_CAP)
3010 cifs_dbg(FYI, "mandatory transport encryption cap\n");
3011 #endif /* CIFS_DEBUG2 */
3012 if (CIFSSMBSetFSUnixInfo(xid, tcon, cap)) {
3014 cifs_dbg(FYI, "resetting capabilities failed\n");
3016 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");
3022 int cifs_setup_cifs_sb(struct cifs_sb_info *cifs_sb)
3024 struct smb3_fs_context *ctx = cifs_sb->ctx;
3026 INIT_DELAYED_WORK(&cifs_sb->prune_tlinks, cifs_prune_tlinks);
3028 spin_lock_init(&cifs_sb->tlink_tree_lock);
3029 cifs_sb->tlink_tree = RB_ROOT;
3031 cifs_dbg(FYI, "file mode: %04ho dir mode: %04ho\n",
3032 ctx->file_mode, ctx->dir_mode);
3034 /* this is needed for ASCII cp to Unicode converts */
3035 if (ctx->iocharset == NULL) {
3036 /* load_nls_default cannot return null */
3037 cifs_sb->local_nls = load_nls_default();
3039 cifs_sb->local_nls = load_nls(ctx->iocharset);
3040 if (cifs_sb->local_nls == NULL) {
3041 cifs_dbg(VFS, "CIFS mount error: iocharset %s not found\n",
3046 ctx->local_nls = cifs_sb->local_nls;
3048 smb3_update_mnt_flags(cifs_sb);
3051 cifs_dbg(FYI, "mounting share using direct i/o\n");
3052 if (ctx->cache_ro) {
3053 cifs_dbg(VFS, "mounting share with read only caching. Ensure that the share will not be modified while in use.\n");
3054 cifs_sb->mnt_cifs_flags |= CIFS_MOUNT_RO_CACHE;
3055 } else if (ctx->cache_rw) {
3056 cifs_dbg(VFS, "mounting share in single client RW caching mode. Ensure that no other systems will be accessing the share.\n");
3057 cifs_sb->mnt_cifs_flags |= (CIFS_MOUNT_RO_CACHE |
3058 CIFS_MOUNT_RW_CACHE);
3061 if ((ctx->cifs_acl) && (ctx->dynperm))
3062 cifs_dbg(VFS, "mount option dynperm ignored if cifsacl mount option supported\n");
3065 cifs_sb->prepath = kstrdup(ctx->prepath, GFP_KERNEL);
3066 if (cifs_sb->prepath == NULL)
3068 cifs_sb->mnt_cifs_flags |= CIFS_MOUNT_USE_PREFIX_PATH;
3074 /* Release all succeed connections */
3075 static inline void mount_put_conns(struct mount_ctx *mnt_ctx)
3080 cifs_put_tcon(mnt_ctx->tcon);
3081 else if (mnt_ctx->ses)
3082 cifs_put_smb_ses(mnt_ctx->ses);
3083 else if (mnt_ctx->server)
3084 cifs_put_tcp_session(mnt_ctx->server, 0);
3085 mnt_ctx->cifs_sb->mnt_cifs_flags &= ~CIFS_MOUNT_POSIX_PATHS;
3086 free_xid(mnt_ctx->xid);
3089 /* Get connections for tcp, ses and tcon */
3090 static int mount_get_conns(struct mount_ctx *mnt_ctx)
3093 struct TCP_Server_Info *server = NULL;
3094 struct cifs_ses *ses = NULL;
3095 struct cifs_tcon *tcon = NULL;
3096 struct smb3_fs_context *ctx = mnt_ctx->fs_ctx;
3097 struct cifs_sb_info *cifs_sb = mnt_ctx->cifs_sb;
3102 /* get a reference to a tcp session */
3103 server = cifs_get_tcp_session(ctx, NULL);
3104 if (IS_ERR(server)) {
3105 rc = PTR_ERR(server);
3110 /* get a reference to a SMB session */
3111 ses = cifs_get_smb_ses(server, ctx);
3118 if ((ctx->persistent == true) && (!(ses->server->capabilities &
3119 SMB2_GLOBAL_CAP_PERSISTENT_HANDLES))) {
3120 cifs_server_dbg(VFS, "persistent handles not supported by server\n");
3125 /* search for existing tcon to this server share */
3126 tcon = cifs_get_tcon(ses, ctx);
3133 /* if new SMB3.11 POSIX extensions are supported do not remap / and \ */
3134 if (tcon->posix_extensions)
3135 cifs_sb->mnt_cifs_flags |= CIFS_MOUNT_POSIX_PATHS;
3137 /* tell server which Unix caps we support */
3138 if (cap_unix(tcon->ses)) {
3140 * reset of caps checks mount to see if unix extensions disabled
3141 * for just this mount.
3143 reset_cifs_unix_caps(xid, tcon, cifs_sb, ctx);
3144 spin_lock(&cifs_tcp_ses_lock);
3145 if ((tcon->ses->server->tcpStatus == CifsNeedReconnect) &&
3146 (le64_to_cpu(tcon->fsUnixInfo.Capability) &
3147 CIFS_UNIX_TRANSPORT_ENCRYPTION_MANDATORY_CAP)) {
3148 spin_unlock(&cifs_tcp_ses_lock);
3152 spin_unlock(&cifs_tcp_ses_lock);
3154 tcon->unix_ext = 0; /* server does not support them */
3156 /* do not care if a following call succeed - informational */
3157 if (!tcon->pipe && server->ops->qfs_tcon) {
3158 server->ops->qfs_tcon(xid, tcon, cifs_sb);
3159 if (cifs_sb->mnt_cifs_flags & CIFS_MOUNT_RO_CACHE) {
3160 if (tcon->fsDevInfo.DeviceCharacteristics &
3161 cpu_to_le32(FILE_READ_ONLY_DEVICE))
3162 cifs_dbg(VFS, "mounted to read only share\n");
3163 else if ((cifs_sb->mnt_cifs_flags &
3164 CIFS_MOUNT_RW_CACHE) == 0)
3165 cifs_dbg(VFS, "read only mount of RW share\n");
3166 /* no need to log a RW mount of a typical RW share */
3171 * Clamp the rsize/wsize mount arguments if they are too big for the server
3172 * and set the rsize/wsize to the negotiated values if not passed in by
3175 if ((cifs_sb->ctx->wsize == 0) ||
3176 (cifs_sb->ctx->wsize > server->ops->negotiate_wsize(tcon, ctx)))
3177 cifs_sb->ctx->wsize = server->ops->negotiate_wsize(tcon, ctx);
3178 if ((cifs_sb->ctx->rsize == 0) ||
3179 (cifs_sb->ctx->rsize > server->ops->negotiate_rsize(tcon, ctx)))
3180 cifs_sb->ctx->rsize = server->ops->negotiate_rsize(tcon, ctx);
3183 * The cookie is initialized from volume info returned above.
3184 * Inside cifs_fscache_get_super_cookie it checks
3185 * that we do not get super cookie twice.
3187 if (cifs_sb->mnt_cifs_flags & CIFS_MOUNT_FSCACHE)
3188 cifs_fscache_get_super_cookie(tcon);
3191 mnt_ctx->server = server;
3193 mnt_ctx->tcon = tcon;
3199 static int mount_setup_tlink(struct cifs_sb_info *cifs_sb, struct cifs_ses *ses,
3200 struct cifs_tcon *tcon)
3202 struct tcon_link *tlink;
3204 /* hang the tcon off of the superblock */
3205 tlink = kzalloc(sizeof(*tlink), GFP_KERNEL);
3209 tlink->tl_uid = ses->linux_uid;
3210 tlink->tl_tcon = tcon;
3211 tlink->tl_time = jiffies;
3212 set_bit(TCON_LINK_MASTER, &tlink->tl_flags);
3213 set_bit(TCON_LINK_IN_TREE, &tlink->tl_flags);
3215 cifs_sb->master_tlink = tlink;
3216 spin_lock(&cifs_sb->tlink_tree_lock);
3217 tlink_rb_insert(&cifs_sb->tlink_tree, tlink);
3218 spin_unlock(&cifs_sb->tlink_tree_lock);
3220 queue_delayed_work(cifsiod_wq, &cifs_sb->prune_tlinks,
3225 #ifdef CONFIG_CIFS_DFS_UPCALL
3226 /* Get unique dfs connections */
3227 static int mount_get_dfs_conns(struct mount_ctx *mnt_ctx)
3231 mnt_ctx->fs_ctx->nosharesock = true;
3232 rc = mount_get_conns(mnt_ctx);
3233 if (mnt_ctx->server) {
3234 cifs_dbg(FYI, "%s: marking tcp session as a dfs connection\n", __func__);
3235 spin_lock(&cifs_tcp_ses_lock);
3236 mnt_ctx->server->is_dfs_conn = true;
3237 spin_unlock(&cifs_tcp_ses_lock);
3243 * cifs_build_path_to_root returns full path to root when we do not have an
3244 * existing connection (tcon)
3247 build_unc_path_to_root(const struct smb3_fs_context *ctx,
3248 const struct cifs_sb_info *cifs_sb, bool useppath)
3250 char *full_path, *pos;
3251 unsigned int pplen = useppath && ctx->prepath ?
3252 strlen(ctx->prepath) + 1 : 0;
3253 unsigned int unc_len = strnlen(ctx->UNC, MAX_TREE_SIZE + 1);
3255 if (unc_len > MAX_TREE_SIZE)
3256 return ERR_PTR(-EINVAL);
3258 full_path = kmalloc(unc_len + pplen + 1, GFP_KERNEL);
3259 if (full_path == NULL)
3260 return ERR_PTR(-ENOMEM);
3262 memcpy(full_path, ctx->UNC, unc_len);
3263 pos = full_path + unc_len;
3266 *pos = CIFS_DIR_SEP(cifs_sb);
3267 memcpy(pos + 1, ctx->prepath, pplen);
3271 *pos = '\0'; /* add trailing null */
3272 convert_delimiter(full_path, CIFS_DIR_SEP(cifs_sb));
3273 cifs_dbg(FYI, "%s: full_path=%s\n", __func__, full_path);
3278 * expand_dfs_referral - Update cifs_sb from dfs referral path
3280 * cifs_sb->ctx->mount_options will be (re-)allocated to a string containing updated options for the
3281 * submount. Otherwise it will be left untouched.
3283 static int expand_dfs_referral(struct mount_ctx *mnt_ctx, const char *full_path,
3284 struct dfs_info3_param *referral)
3287 struct cifs_sb_info *cifs_sb = mnt_ctx->cifs_sb;
3288 struct smb3_fs_context *ctx = mnt_ctx->fs_ctx;
3289 char *fake_devname = NULL, *mdata = NULL;
3291 mdata = cifs_compose_mount_options(cifs_sb->ctx->mount_options, full_path + 1, referral,
3293 if (IS_ERR(mdata)) {
3294 rc = PTR_ERR(mdata);
3298 * We can not clear out the whole structure since we no longer have an explicit
3299 * function to parse a mount-string. Instead we need to clear out the individual
3300 * fields that are no longer valid.
3302 kfree(ctx->prepath);
3303 ctx->prepath = NULL;
3304 rc = cifs_setup_volume_info(ctx, mdata, fake_devname);
3306 kfree(fake_devname);
3307 kfree(cifs_sb->ctx->mount_options);
3308 cifs_sb->ctx->mount_options = mdata;
3314 /* TODO: all callers to this are broken. We are not parsing mount_options here
3315 * we should pass a clone of the original context?
3318 cifs_setup_volume_info(struct smb3_fs_context *ctx, const char *mntopts, const char *devname)
3323 cifs_dbg(FYI, "%s: devname=%s\n", __func__, devname);
3324 rc = smb3_parse_devname(devname, ctx);
3326 cifs_dbg(VFS, "%s: failed to parse %s: %d\n", __func__, devname, rc);
3334 rc = smb3_parse_opt(mntopts, "ip", &ip);
3336 cifs_dbg(VFS, "%s: failed to parse ip options: %d\n", __func__, rc);
3340 rc = cifs_convert_address((struct sockaddr *)&ctx->dstaddr, ip, strlen(ip));
3343 cifs_dbg(VFS, "%s: failed to convert ip address\n", __func__);
3348 if (ctx->nullauth) {
3349 cifs_dbg(FYI, "Anonymous login\n");
3350 kfree(ctx->username);
3351 ctx->username = NULL;
3352 } else if (ctx->username) {
3353 /* BB fixme parse for domain name here */
3354 cifs_dbg(FYI, "Username: %s\n", ctx->username);
3356 cifs_dbg(VFS, "No username specified\n");
3357 /* In userspace mount helper we can get user name from alternate
3358 locations such as env variables and files on disk */
3366 cifs_are_all_path_components_accessible(struct TCP_Server_Info *server,
3368 struct cifs_tcon *tcon,
3369 struct cifs_sb_info *cifs_sb,
3376 int skip = added_treename ? 1 : 0;
3378 sep = CIFS_DIR_SEP(cifs_sb);
3381 rc = server->ops->is_path_accessible(xid, tcon, cifs_sb, "");
3383 /* skip separators */
3388 /* next separator */
3389 while (*s && *s != sep)
3392 * if the treename is added, we then have to skip the first
3393 * part within the separators
3400 * temporarily null-terminate the path at the end of
3401 * the current component
3405 rc = server->ops->is_path_accessible(xid, tcon, cifs_sb,
3413 * Check if path is remote (e.g. a DFS share). Return -EREMOTE if it is,
3416 static int is_path_remote(struct mount_ctx *mnt_ctx)
3419 struct cifs_sb_info *cifs_sb = mnt_ctx->cifs_sb;
3420 struct TCP_Server_Info *server = mnt_ctx->server;
3421 unsigned int xid = mnt_ctx->xid;
3422 struct cifs_tcon *tcon = mnt_ctx->tcon;
3423 struct smb3_fs_context *ctx = mnt_ctx->fs_ctx;
3426 if (!server->ops->is_path_accessible)
3430 * cifs_build_path_to_root works only when we have a valid tcon
3432 full_path = cifs_build_path_to_root(ctx, cifs_sb, tcon,
3433 tcon->Flags & SMB_SHARE_IS_IN_DFS);
3434 if (full_path == NULL)
3437 cifs_dbg(FYI, "%s: full_path: %s\n", __func__, full_path);
3439 rc = server->ops->is_path_accessible(xid, tcon, cifs_sb,
3441 #ifdef CONFIG_CIFS_DFS_UPCALL
3442 if (rc == -ENOENT && is_tcon_dfs(tcon))
3443 rc = cifs_dfs_query_info_nonascii_quirk(xid, tcon, cifs_sb,
3446 if (rc != 0 && rc != -EREMOTE) {
3451 if (rc != -EREMOTE) {
3452 rc = cifs_are_all_path_components_accessible(server, xid, tcon,
3453 cifs_sb, full_path, tcon->Flags & SMB_SHARE_IS_IN_DFS);
3455 cifs_server_dbg(VFS, "cannot query dirs between root and final path, enabling CIFS_MOUNT_USE_PREFIX_PATH\n");
3456 cifs_sb->mnt_cifs_flags |= CIFS_MOUNT_USE_PREFIX_PATH;
3465 #ifdef CONFIG_CIFS_DFS_UPCALL
3466 static void set_root_ses(struct mount_ctx *mnt_ctx)
3469 spin_lock(&cifs_tcp_ses_lock);
3470 mnt_ctx->ses->ses_count++;
3471 spin_unlock(&cifs_tcp_ses_lock);
3472 dfs_cache_add_refsrv_session(&mnt_ctx->mount_id, mnt_ctx->ses);
3474 mnt_ctx->root_ses = mnt_ctx->ses;
3477 static int is_dfs_mount(struct mount_ctx *mnt_ctx, bool *isdfs, struct dfs_cache_tgt_list *root_tl)
3480 struct cifs_sb_info *cifs_sb = mnt_ctx->cifs_sb;
3481 struct smb3_fs_context *ctx = mnt_ctx->fs_ctx;
3485 rc = mount_get_conns(mnt_ctx);
3487 * If called with 'nodfs' mount option, then skip DFS resolving. Otherwise unconditionally
3488 * try to get an DFS referral (even cached) to determine whether it is an DFS mount.
3490 * Skip prefix path to provide support for DFS referrals from w2k8 servers which don't seem
3491 * to respond with PATH_NOT_COVERED to requests that include the prefix.
3493 if ((cifs_sb->mnt_cifs_flags & CIFS_MOUNT_NO_DFS) ||
3494 dfs_cache_find(mnt_ctx->xid, mnt_ctx->ses, cifs_sb->local_nls, cifs_remap(cifs_sb),
3495 ctx->UNC + 1, NULL, root_tl)) {
3498 /* Check if it is fully accessible and then mount it */
3499 rc = is_path_remote(mnt_ctx);
3502 else if (rc != -EREMOTE)
3508 static int connect_dfs_target(struct mount_ctx *mnt_ctx, const char *full_path,
3509 const char *ref_path, struct dfs_cache_tgt_iterator *tit)
3512 struct dfs_info3_param ref = {};
3513 struct cifs_sb_info *cifs_sb = mnt_ctx->cifs_sb;
3514 char *oldmnt = cifs_sb->ctx->mount_options;
3516 cifs_dbg(FYI, "%s: full_path=%s ref_path=%s target=%s\n", __func__, full_path, ref_path,
3517 dfs_cache_get_tgt_name(tit));
3519 rc = dfs_cache_get_tgt_referral(ref_path, tit, &ref);
3523 rc = expand_dfs_referral(mnt_ctx, full_path, &ref);
3527 /* Connect to new target only if we were redirected (e.g. mount options changed) */
3528 if (oldmnt != cifs_sb->ctx->mount_options) {
3529 mount_put_conns(mnt_ctx);
3530 rc = mount_get_dfs_conns(mnt_ctx);
3533 if (cifs_is_referral_server(mnt_ctx->tcon, &ref))
3534 set_root_ses(mnt_ctx);
3535 rc = dfs_cache_update_tgthint(mnt_ctx->xid, mnt_ctx->root_ses, cifs_sb->local_nls,
3536 cifs_remap(cifs_sb), ref_path, tit);
3540 free_dfs_info_param(&ref);
3544 static int connect_dfs_root(struct mount_ctx *mnt_ctx, struct dfs_cache_tgt_list *root_tl)
3548 struct cifs_sb_info *cifs_sb = mnt_ctx->cifs_sb;
3549 struct smb3_fs_context *ctx = mnt_ctx->fs_ctx;
3550 struct dfs_cache_tgt_iterator *tit;
3552 /* Put initial connections as they might be shared with other mounts. We need unique dfs
3553 * connections per mount to properly failover, so mount_get_dfs_conns() must be used from
3556 mount_put_conns(mnt_ctx);
3557 mount_get_dfs_conns(mnt_ctx);
3558 set_root_ses(mnt_ctx);
3560 full_path = build_unc_path_to_root(ctx, cifs_sb, true);
3561 if (IS_ERR(full_path))
3562 return PTR_ERR(full_path);
3564 mnt_ctx->origin_fullpath = dfs_cache_canonical_path(ctx->UNC, cifs_sb->local_nls,
3565 cifs_remap(cifs_sb));
3566 if (IS_ERR(mnt_ctx->origin_fullpath)) {
3567 rc = PTR_ERR(mnt_ctx->origin_fullpath);
3568 mnt_ctx->origin_fullpath = NULL;
3572 /* Try all dfs root targets */
3573 for (rc = -ENOENT, tit = dfs_cache_get_tgt_iterator(root_tl);
3574 tit; tit = dfs_cache_get_next_tgt(root_tl, tit)) {
3575 rc = connect_dfs_target(mnt_ctx, full_path, mnt_ctx->origin_fullpath + 1, tit);
3577 mnt_ctx->leaf_fullpath = kstrdup(mnt_ctx->origin_fullpath, GFP_KERNEL);
3578 if (!mnt_ctx->leaf_fullpath)
3589 static int __follow_dfs_link(struct mount_ctx *mnt_ctx)
3592 struct cifs_sb_info *cifs_sb = mnt_ctx->cifs_sb;
3593 struct smb3_fs_context *ctx = mnt_ctx->fs_ctx;
3595 struct dfs_cache_tgt_list tl = DFS_CACHE_TGT_LIST_INIT(tl);
3596 struct dfs_cache_tgt_iterator *tit;
3598 full_path = build_unc_path_to_root(ctx, cifs_sb, true);
3599 if (IS_ERR(full_path))
3600 return PTR_ERR(full_path);
3602 kfree(mnt_ctx->leaf_fullpath);
3603 mnt_ctx->leaf_fullpath = dfs_cache_canonical_path(full_path, cifs_sb->local_nls,
3604 cifs_remap(cifs_sb));
3605 if (IS_ERR(mnt_ctx->leaf_fullpath)) {
3606 rc = PTR_ERR(mnt_ctx->leaf_fullpath);
3607 mnt_ctx->leaf_fullpath = NULL;
3611 /* Get referral from dfs link */
3612 rc = dfs_cache_find(mnt_ctx->xid, mnt_ctx->root_ses, cifs_sb->local_nls,
3613 cifs_remap(cifs_sb), mnt_ctx->leaf_fullpath + 1, NULL, &tl);
3617 /* Try all dfs link targets. If an I/O fails from currently connected DFS target with an
3618 * error other than STATUS_PATH_NOT_COVERED (-EREMOTE), then retry it from other targets as
3619 * specified in MS-DFSC "3.1.5.2 I/O Operation to Target Fails with an Error Other Than
3620 * STATUS_PATH_NOT_COVERED."
3622 for (rc = -ENOENT, tit = dfs_cache_get_tgt_iterator(&tl);
3623 tit; tit = dfs_cache_get_next_tgt(&tl, tit)) {
3624 rc = connect_dfs_target(mnt_ctx, full_path, mnt_ctx->leaf_fullpath + 1, tit);
3626 rc = is_path_remote(mnt_ctx);
3627 if (!rc || rc == -EREMOTE)
3634 dfs_cache_free_tgts(&tl);
3638 static int follow_dfs_link(struct mount_ctx *mnt_ctx)
3641 struct cifs_sb_info *cifs_sb = mnt_ctx->cifs_sb;
3642 struct smb3_fs_context *ctx = mnt_ctx->fs_ctx;
3646 full_path = build_unc_path_to_root(ctx, cifs_sb, true);
3647 if (IS_ERR(full_path))
3648 return PTR_ERR(full_path);
3650 kfree(mnt_ctx->origin_fullpath);
3651 mnt_ctx->origin_fullpath = dfs_cache_canonical_path(full_path, cifs_sb->local_nls,
3652 cifs_remap(cifs_sb));
3655 if (IS_ERR(mnt_ctx->origin_fullpath)) {
3656 rc = PTR_ERR(mnt_ctx->origin_fullpath);
3657 mnt_ctx->origin_fullpath = NULL;
3662 rc = __follow_dfs_link(mnt_ctx);
3663 if (!rc || rc != -EREMOTE)
3665 } while (rc = -ELOOP, ++num_links < MAX_NESTED_LINKS);
3670 /* Set up DFS referral paths for failover */
3671 static void setup_server_referral_paths(struct mount_ctx *mnt_ctx)
3673 struct TCP_Server_Info *server = mnt_ctx->server;
3675 server->origin_fullpath = mnt_ctx->origin_fullpath;
3676 server->leaf_fullpath = mnt_ctx->leaf_fullpath;
3677 server->current_fullpath = mnt_ctx->leaf_fullpath;
3678 mnt_ctx->origin_fullpath = mnt_ctx->leaf_fullpath = NULL;
3681 int cifs_mount(struct cifs_sb_info *cifs_sb, struct smb3_fs_context *ctx)
3684 struct mount_ctx mnt_ctx = { .cifs_sb = cifs_sb, .fs_ctx = ctx, };
3685 struct dfs_cache_tgt_list tl = DFS_CACHE_TGT_LIST_INIT(tl);
3688 rc = is_dfs_mount(&mnt_ctx, &isdfs, &tl);
3694 uuid_gen(&mnt_ctx.mount_id);
3695 rc = connect_dfs_root(&mnt_ctx, &tl);
3696 dfs_cache_free_tgts(&tl);
3701 rc = is_path_remote(&mnt_ctx);
3703 rc = follow_dfs_link(&mnt_ctx);
3707 setup_server_referral_paths(&mnt_ctx);
3709 * After reconnecting to a different server, unique ids won't match anymore, so we disable
3710 * serverino. This prevents dentry revalidation to think the dentry are stale (ESTALE).
3712 cifs_autodisable_serverino(cifs_sb);
3714 * Force the use of prefix path to support failover on DFS paths that resolve to targets
3715 * that have different prefix paths.
3717 cifs_sb->mnt_cifs_flags |= CIFS_MOUNT_USE_PREFIX_PATH;
3718 kfree(cifs_sb->prepath);
3719 cifs_sb->prepath = ctx->prepath;
3720 ctx->prepath = NULL;
3721 uuid_copy(&cifs_sb->dfs_mount_id, &mnt_ctx.mount_id);
3724 free_xid(mnt_ctx.xid);
3725 cifs_try_adding_channels(cifs_sb, mnt_ctx.ses);
3726 return mount_setup_tlink(cifs_sb, mnt_ctx.ses, mnt_ctx.tcon);
3729 dfs_cache_put_refsrv_sessions(&mnt_ctx.mount_id);
3730 kfree(mnt_ctx.origin_fullpath);
3731 kfree(mnt_ctx.leaf_fullpath);
3732 mount_put_conns(&mnt_ctx);
3736 int cifs_mount(struct cifs_sb_info *cifs_sb, struct smb3_fs_context *ctx)
3739 struct mount_ctx mnt_ctx = { .cifs_sb = cifs_sb, .fs_ctx = ctx, };
3741 rc = mount_get_conns(&mnt_ctx);
3746 rc = is_path_remote(&mnt_ctx);
3753 free_xid(mnt_ctx.xid);
3754 return mount_setup_tlink(cifs_sb, mnt_ctx.ses, mnt_ctx.tcon);
3757 mount_put_conns(&mnt_ctx);
3763 * Issue a TREE_CONNECT request.
3766 CIFSTCon(const unsigned int xid, struct cifs_ses *ses,
3767 const char *tree, struct cifs_tcon *tcon,
3768 const struct nls_table *nls_codepage)
3770 struct smb_hdr *smb_buffer;
3771 struct smb_hdr *smb_buffer_response;
3774 unsigned char *bcc_ptr;
3777 __u16 bytes_left, count;
3782 smb_buffer = cifs_buf_get();
3783 if (smb_buffer == NULL)
3786 smb_buffer_response = smb_buffer;
3788 header_assemble(smb_buffer, SMB_COM_TREE_CONNECT_ANDX,
3789 NULL /*no tid */ , 4 /*wct */ );
3791 smb_buffer->Mid = get_next_mid(ses->server);
3792 smb_buffer->Uid = ses->Suid;
3793 pSMB = (TCONX_REQ *) smb_buffer;
3794 pSMBr = (TCONX_RSP *) smb_buffer_response;
3796 pSMB->AndXCommand = 0xFF;
3797 pSMB->Flags = cpu_to_le16(TCON_EXTENDED_SECINFO);
3798 bcc_ptr = &pSMB->Password[0];
3799 if (tcon->pipe || (ses->server->sec_mode & SECMODE_USER)) {
3800 pSMB->PasswordLength = cpu_to_le16(1); /* minimum */
3801 *bcc_ptr = 0; /* password is null byte */
3802 bcc_ptr++; /* skip password */
3803 /* already aligned so no need to do it below */
3806 if (ses->server->sign)
3807 smb_buffer->Flags2 |= SMBFLG2_SECURITY_SIGNATURE;
3809 if (ses->capabilities & CAP_STATUS32) {
3810 smb_buffer->Flags2 |= SMBFLG2_ERR_STATUS;
3812 if (ses->capabilities & CAP_DFS) {
3813 smb_buffer->Flags2 |= SMBFLG2_DFS;
3815 if (ses->capabilities & CAP_UNICODE) {
3816 smb_buffer->Flags2 |= SMBFLG2_UNICODE;
3818 cifs_strtoUTF16((__le16 *) bcc_ptr, tree,
3819 6 /* max utf8 char length in bytes */ *
3820 (/* server len*/ + 256 /* share len */), nls_codepage);
3821 bcc_ptr += 2 * length; /* convert num 16 bit words to bytes */
3822 bcc_ptr += 2; /* skip trailing null */
3823 } else { /* ASCII */
3824 strcpy(bcc_ptr, tree);
3825 bcc_ptr += strlen(tree) + 1;
3827 strcpy(bcc_ptr, "?????");
3828 bcc_ptr += strlen("?????");
3830 count = bcc_ptr - &pSMB->Password[0];
3831 be32_add_cpu(&pSMB->hdr.smb_buf_length, count);
3832 pSMB->ByteCount = cpu_to_le16(count);
3834 rc = SendReceive(xid, ses, smb_buffer, smb_buffer_response, &length,
3837 /* above now done in SendReceive */
3841 tcon->tid = smb_buffer_response->Tid;
3842 bcc_ptr = pByteArea(smb_buffer_response);
3843 bytes_left = get_bcc(smb_buffer_response);
3844 length = strnlen(bcc_ptr, bytes_left - 2);
3845 if (smb_buffer->Flags2 & SMBFLG2_UNICODE)
3851 /* skip service field (NB: this field is always ASCII) */
3853 if ((bcc_ptr[0] == 'I') && (bcc_ptr[1] == 'P') &&
3854 (bcc_ptr[2] == 'C')) {
3855 cifs_dbg(FYI, "IPC connection\n");
3859 } else if (length == 2) {
3860 if ((bcc_ptr[0] == 'A') && (bcc_ptr[1] == ':')) {
3861 /* the most common case */
3862 cifs_dbg(FYI, "disk share connection\n");
3865 bcc_ptr += length + 1;
3866 bytes_left -= (length + 1);
3867 strlcpy(tcon->treeName, tree, sizeof(tcon->treeName));
3869 /* mostly informational -- no need to fail on error here */
3870 kfree(tcon->nativeFileSystem);
3871 tcon->nativeFileSystem = cifs_strndup_from_utf16(bcc_ptr,
3872 bytes_left, is_unicode,
3875 cifs_dbg(FYI, "nativeFileSystem=%s\n", tcon->nativeFileSystem);
3877 if ((smb_buffer_response->WordCount == 3) ||
3878 (smb_buffer_response->WordCount == 7))
3879 /* field is in same location */
3880 tcon->Flags = le16_to_cpu(pSMBr->OptionalSupport);
3883 cifs_dbg(FYI, "Tcon flags: 0x%x\n", tcon->Flags);
3886 cifs_buf_release(smb_buffer);
3890 static void delayed_free(struct rcu_head *p)
3892 struct cifs_sb_info *cifs_sb = container_of(p, struct cifs_sb_info, rcu);
3894 unload_nls(cifs_sb->local_nls);
3895 smb3_cleanup_fs_context(cifs_sb->ctx);
3900 cifs_umount(struct cifs_sb_info *cifs_sb)
3902 struct rb_root *root = &cifs_sb->tlink_tree;
3903 struct rb_node *node;
3904 struct tcon_link *tlink;
3906 cancel_delayed_work_sync(&cifs_sb->prune_tlinks);
3908 spin_lock(&cifs_sb->tlink_tree_lock);
3909 while ((node = rb_first(root))) {
3910 tlink = rb_entry(node, struct tcon_link, tl_rbnode);
3911 cifs_get_tlink(tlink);
3912 clear_bit(TCON_LINK_IN_TREE, &tlink->tl_flags);
3913 rb_erase(node, root);
3915 spin_unlock(&cifs_sb->tlink_tree_lock);
3916 cifs_put_tlink(tlink);
3917 spin_lock(&cifs_sb->tlink_tree_lock);
3919 spin_unlock(&cifs_sb->tlink_tree_lock);
3921 kfree(cifs_sb->prepath);
3922 #ifdef CONFIG_CIFS_DFS_UPCALL
3923 dfs_cache_put_refsrv_sessions(&cifs_sb->dfs_mount_id);
3925 call_rcu(&cifs_sb->rcu, delayed_free);
3929 cifs_negotiate_protocol(const unsigned int xid, struct cifs_ses *ses,
3930 struct TCP_Server_Info *server)
3934 if (!server->ops->need_neg || !server->ops->negotiate)
3937 /* only send once per connect */
3938 spin_lock(&cifs_tcp_ses_lock);
3939 if (!server->ops->need_neg(server) ||
3940 server->tcpStatus != CifsNeedNegotiate) {
3941 spin_unlock(&cifs_tcp_ses_lock);
3944 server->tcpStatus = CifsInNegotiate;
3945 spin_unlock(&cifs_tcp_ses_lock);
3947 rc = server->ops->negotiate(xid, ses, server);
3949 spin_lock(&cifs_tcp_ses_lock);
3950 if (server->tcpStatus == CifsInNegotiate)
3951 server->tcpStatus = CifsNeedSessSetup;
3954 spin_unlock(&cifs_tcp_ses_lock);
3956 spin_lock(&cifs_tcp_ses_lock);
3957 if (server->tcpStatus == CifsInNegotiate)
3958 server->tcpStatus = CifsNeedNegotiate;
3959 spin_unlock(&cifs_tcp_ses_lock);
3966 cifs_setup_session(const unsigned int xid, struct cifs_ses *ses,
3967 struct TCP_Server_Info *server,
3968 struct nls_table *nls_info)
3971 bool is_binding = false;
3973 /* only send once per connect */
3974 spin_lock(&cifs_tcp_ses_lock);
3975 if ((server->tcpStatus != CifsNeedSessSetup) &&
3976 (ses->status == CifsGood)) {
3977 spin_unlock(&cifs_tcp_ses_lock);
3980 server->tcpStatus = CifsInSessSetup;
3981 spin_unlock(&cifs_tcp_ses_lock);
3983 spin_lock(&ses->chan_lock);
3984 is_binding = !CIFS_ALL_CHANS_NEED_RECONNECT(ses);
3985 spin_unlock(&ses->chan_lock);
3988 ses->capabilities = server->capabilities;
3989 if (!linuxExtEnabled)
3990 ses->capabilities &= (~server->vals->cap_unix);
3992 if (ses->auth_key.response) {
3993 cifs_dbg(FYI, "Free previous auth_key.response = %p\n",
3994 ses->auth_key.response);
3995 kfree(ses->auth_key.response);
3996 ses->auth_key.response = NULL;
3997 ses->auth_key.len = 0;
4001 cifs_dbg(FYI, "Security Mode: 0x%x Capabilities: 0x%x TimeAdjust: %d\n",
4002 server->sec_mode, server->capabilities, server->timeAdj);
4004 if (server->ops->sess_setup)
4005 rc = server->ops->sess_setup(xid, ses, server, nls_info);
4008 cifs_server_dbg(VFS, "Send error in SessSetup = %d\n", rc);
4009 spin_lock(&cifs_tcp_ses_lock);
4010 if (server->tcpStatus == CifsInSessSetup)
4011 server->tcpStatus = CifsNeedSessSetup;
4012 spin_unlock(&cifs_tcp_ses_lock);
4014 spin_lock(&cifs_tcp_ses_lock);
4015 if (server->tcpStatus == CifsInSessSetup)
4016 server->tcpStatus = CifsGood;
4017 /* Even if one channel is active, session is in good state */
4018 ses->status = CifsGood;
4019 spin_unlock(&cifs_tcp_ses_lock);
4021 spin_lock(&ses->chan_lock);
4022 cifs_chan_clear_need_reconnect(ses, server);
4023 spin_unlock(&ses->chan_lock);
4030 cifs_set_vol_auth(struct smb3_fs_context *ctx, struct cifs_ses *ses)
4032 ctx->sectype = ses->sectype;
4034 /* krb5 is special, since we don't need username or pw */
4035 if (ctx->sectype == Kerberos)
4038 return cifs_set_cifscreds(ctx, ses);
4041 static struct cifs_tcon *
4042 cifs_construct_tcon(struct cifs_sb_info *cifs_sb, kuid_t fsuid)
4045 struct cifs_tcon *master_tcon = cifs_sb_master_tcon(cifs_sb);
4046 struct cifs_ses *ses;
4047 struct cifs_tcon *tcon = NULL;
4048 struct smb3_fs_context *ctx;
4050 ctx = kzalloc(sizeof(*ctx), GFP_KERNEL);
4052 return ERR_PTR(-ENOMEM);
4054 ctx->local_nls = cifs_sb->local_nls;
4055 ctx->linux_uid = fsuid;
4056 ctx->cred_uid = fsuid;
4057 ctx->UNC = master_tcon->treeName;
4058 ctx->retry = master_tcon->retry;
4059 ctx->nocase = master_tcon->nocase;
4060 ctx->nohandlecache = master_tcon->nohandlecache;
4061 ctx->local_lease = master_tcon->local_lease;
4062 ctx->no_lease = master_tcon->no_lease;
4063 ctx->resilient = master_tcon->use_resilient;
4064 ctx->persistent = master_tcon->use_persistent;
4065 ctx->handle_timeout = master_tcon->handle_timeout;
4066 ctx->no_linux_ext = !master_tcon->unix_ext;
4067 ctx->linux_ext = master_tcon->posix_extensions;
4068 ctx->sectype = master_tcon->ses->sectype;
4069 ctx->sign = master_tcon->ses->sign;
4070 ctx->seal = master_tcon->seal;
4071 ctx->witness = master_tcon->use_witness;
4073 rc = cifs_set_vol_auth(ctx, master_tcon->ses);
4079 /* get a reference for the same TCP session */
4080 spin_lock(&cifs_tcp_ses_lock);
4081 ++master_tcon->ses->server->srv_count;
4082 spin_unlock(&cifs_tcp_ses_lock);
4084 ses = cifs_get_smb_ses(master_tcon->ses->server, ctx);
4086 tcon = (struct cifs_tcon *)ses;
4087 cifs_put_tcp_session(master_tcon->ses->server, 0);
4091 tcon = cifs_get_tcon(ses, ctx);
4093 cifs_put_smb_ses(ses);
4098 reset_cifs_unix_caps(0, tcon, NULL, ctx);
4101 kfree(ctx->username);
4102 kfree_sensitive(ctx->password);
4109 cifs_sb_master_tcon(struct cifs_sb_info *cifs_sb)
4111 return tlink_tcon(cifs_sb_master_tlink(cifs_sb));
4114 /* find and return a tlink with given uid */
4115 static struct tcon_link *
4116 tlink_rb_search(struct rb_root *root, kuid_t uid)
4118 struct rb_node *node = root->rb_node;
4119 struct tcon_link *tlink;
4122 tlink = rb_entry(node, struct tcon_link, tl_rbnode);
4124 if (uid_gt(tlink->tl_uid, uid))
4125 node = node->rb_left;
4126 else if (uid_lt(tlink->tl_uid, uid))
4127 node = node->rb_right;
4134 /* insert a tcon_link into the tree */
4136 tlink_rb_insert(struct rb_root *root, struct tcon_link *new_tlink)
4138 struct rb_node **new = &(root->rb_node), *parent = NULL;
4139 struct tcon_link *tlink;
4142 tlink = rb_entry(*new, struct tcon_link, tl_rbnode);
4145 if (uid_gt(tlink->tl_uid, new_tlink->tl_uid))
4146 new = &((*new)->rb_left);
4148 new = &((*new)->rb_right);
4151 rb_link_node(&new_tlink->tl_rbnode, parent, new);
4152 rb_insert_color(&new_tlink->tl_rbnode, root);
4156 * Find or construct an appropriate tcon given a cifs_sb and the fsuid of the
4159 * If the superblock doesn't refer to a multiuser mount, then just return
4160 * the master tcon for the mount.
4162 * First, search the rbtree for an existing tcon for this fsuid. If one
4163 * exists, then check to see if it's pending construction. If it is then wait
4164 * for construction to complete. Once it's no longer pending, check to see if
4165 * it failed and either return an error or retry construction, depending on
4168 * If one doesn't exist then insert a new tcon_link struct into the tree and
4169 * try to construct a new one.
4172 cifs_sb_tlink(struct cifs_sb_info *cifs_sb)
4175 kuid_t fsuid = current_fsuid();
4176 struct tcon_link *tlink, *newtlink;
4178 if (!(cifs_sb->mnt_cifs_flags & CIFS_MOUNT_MULTIUSER))
4179 return cifs_get_tlink(cifs_sb_master_tlink(cifs_sb));
4181 spin_lock(&cifs_sb->tlink_tree_lock);
4182 tlink = tlink_rb_search(&cifs_sb->tlink_tree, fsuid);
4184 cifs_get_tlink(tlink);
4185 spin_unlock(&cifs_sb->tlink_tree_lock);
4187 if (tlink == NULL) {
4188 newtlink = kzalloc(sizeof(*tlink), GFP_KERNEL);
4189 if (newtlink == NULL)
4190 return ERR_PTR(-ENOMEM);
4191 newtlink->tl_uid = fsuid;
4192 newtlink->tl_tcon = ERR_PTR(-EACCES);
4193 set_bit(TCON_LINK_PENDING, &newtlink->tl_flags);
4194 set_bit(TCON_LINK_IN_TREE, &newtlink->tl_flags);
4195 cifs_get_tlink(newtlink);
4197 spin_lock(&cifs_sb->tlink_tree_lock);
4198 /* was one inserted after previous search? */
4199 tlink = tlink_rb_search(&cifs_sb->tlink_tree, fsuid);
4201 cifs_get_tlink(tlink);
4202 spin_unlock(&cifs_sb->tlink_tree_lock);
4204 goto wait_for_construction;
4207 tlink_rb_insert(&cifs_sb->tlink_tree, tlink);
4208 spin_unlock(&cifs_sb->tlink_tree_lock);
4210 wait_for_construction:
4211 ret = wait_on_bit(&tlink->tl_flags, TCON_LINK_PENDING,
4212 TASK_INTERRUPTIBLE);
4214 cifs_put_tlink(tlink);
4215 return ERR_PTR(-ERESTARTSYS);
4218 /* if it's good, return it */
4219 if (!IS_ERR(tlink->tl_tcon))
4222 /* return error if we tried this already recently */
4223 if (time_before(jiffies, tlink->tl_time + TLINK_ERROR_EXPIRE)) {
4224 cifs_put_tlink(tlink);
4225 return ERR_PTR(-EACCES);
4228 if (test_and_set_bit(TCON_LINK_PENDING, &tlink->tl_flags))
4229 goto wait_for_construction;
4232 tlink->tl_tcon = cifs_construct_tcon(cifs_sb, fsuid);
4233 clear_bit(TCON_LINK_PENDING, &tlink->tl_flags);
4234 wake_up_bit(&tlink->tl_flags, TCON_LINK_PENDING);
4236 if (IS_ERR(tlink->tl_tcon)) {
4237 cifs_put_tlink(tlink);
4238 return ERR_PTR(-EACCES);
4245 * periodic workqueue job that scans tcon_tree for a superblock and closes
4249 cifs_prune_tlinks(struct work_struct *work)
4251 struct cifs_sb_info *cifs_sb = container_of(work, struct cifs_sb_info,
4253 struct rb_root *root = &cifs_sb->tlink_tree;
4254 struct rb_node *node;
4255 struct rb_node *tmp;
4256 struct tcon_link *tlink;
4259 * Because we drop the spinlock in the loop in order to put the tlink
4260 * it's not guarded against removal of links from the tree. The only
4261 * places that remove entries from the tree are this function and
4262 * umounts. Because this function is non-reentrant and is canceled
4263 * before umount can proceed, this is safe.
4265 spin_lock(&cifs_sb->tlink_tree_lock);
4266 node = rb_first(root);
4267 while (node != NULL) {
4269 node = rb_next(tmp);
4270 tlink = rb_entry(tmp, struct tcon_link, tl_rbnode);
4272 if (test_bit(TCON_LINK_MASTER, &tlink->tl_flags) ||
4273 atomic_read(&tlink->tl_count) != 0 ||
4274 time_after(tlink->tl_time + TLINK_IDLE_EXPIRE, jiffies))
4277 cifs_get_tlink(tlink);
4278 clear_bit(TCON_LINK_IN_TREE, &tlink->tl_flags);
4279 rb_erase(tmp, root);
4281 spin_unlock(&cifs_sb->tlink_tree_lock);
4282 cifs_put_tlink(tlink);
4283 spin_lock(&cifs_sb->tlink_tree_lock);
4285 spin_unlock(&cifs_sb->tlink_tree_lock);
4287 queue_delayed_work(cifsiod_wq, &cifs_sb->prune_tlinks,
4291 #ifdef CONFIG_CIFS_DFS_UPCALL
4292 /* Update dfs referral path of superblock */
4293 static int update_server_fullpath(struct TCP_Server_Info *server, struct cifs_sb_info *cifs_sb,
4297 size_t len = strlen(target);
4298 char *refpath, *npath;
4300 if (unlikely(len < 2 || *target != '\\'))
4303 if (target[1] == '\\') {
4305 refpath = kmalloc(len, GFP_KERNEL);
4309 scnprintf(refpath, len, "%s", target);
4311 len += sizeof("\\");
4312 refpath = kmalloc(len, GFP_KERNEL);
4316 scnprintf(refpath, len, "\\%s", target);
4319 npath = dfs_cache_canonical_path(refpath, cifs_sb->local_nls, cifs_remap(cifs_sb));
4322 if (IS_ERR(npath)) {
4323 rc = PTR_ERR(npath);
4325 mutex_lock(&server->refpath_lock);
4326 kfree(server->leaf_fullpath);
4327 server->leaf_fullpath = npath;
4328 mutex_unlock(&server->refpath_lock);
4329 server->current_fullpath = server->leaf_fullpath;
4334 static int target_share_matches_server(struct TCP_Server_Info *server, const char *tcp_host,
4335 size_t tcp_host_len, char *share, bool *target_match)
4338 const char *dfs_host;
4339 size_t dfs_host_len;
4341 *target_match = true;
4342 extract_unc_hostname(share, &dfs_host, &dfs_host_len);
4344 /* Check if hostnames or addresses match */
4345 if (dfs_host_len != tcp_host_len || strncasecmp(dfs_host, tcp_host, dfs_host_len) != 0) {
4346 cifs_dbg(FYI, "%s: %.*s doesn't match %.*s\n", __func__, (int)dfs_host_len,
4347 dfs_host, (int)tcp_host_len, tcp_host);
4348 rc = match_target_ip(server, dfs_host, dfs_host_len, target_match);
4350 cifs_dbg(VFS, "%s: failed to match target ip: %d\n", __func__, rc);
4355 static int __tree_connect_dfs_target(const unsigned int xid, struct cifs_tcon *tcon,
4356 struct cifs_sb_info *cifs_sb, char *tree, bool islink,
4357 struct dfs_cache_tgt_list *tl)
4360 struct TCP_Server_Info *server = tcon->ses->server;
4361 const struct smb_version_operations *ops = server->ops;
4362 struct cifs_tcon *ipc = tcon->ses->tcon_ipc;
4363 char *share = NULL, *prefix = NULL;
4364 const char *tcp_host;
4365 size_t tcp_host_len;
4366 struct dfs_cache_tgt_iterator *tit;
4369 extract_unc_hostname(server->hostname, &tcp_host, &tcp_host_len);
4371 tit = dfs_cache_get_tgt_iterator(tl);
4377 /* Try to tree connect to all dfs targets */
4378 for (; tit; tit = dfs_cache_get_next_tgt(tl, tit)) {
4379 const char *target = dfs_cache_get_tgt_name(tit);
4380 struct dfs_cache_tgt_list ntl = DFS_CACHE_TGT_LIST_INIT(ntl);
4384 share = prefix = NULL;
4386 /* Check if share matches with tcp ses */
4387 rc = dfs_cache_get_tgt_share(server->current_fullpath + 1, tit, &share, &prefix);
4389 cifs_dbg(VFS, "%s: failed to parse target share: %d\n", __func__, rc);
4393 rc = target_share_matches_server(server, tcp_host, tcp_host_len, share,
4397 if (!target_match) {
4402 if (ipc->need_reconnect) {
4403 scnprintf(tree, MAX_TREE_SIZE, "\\\\%s\\IPC$", server->hostname);
4404 rc = ops->tree_connect(xid, ipc->ses, tree, ipc, cifs_sb->local_nls);
4409 scnprintf(tree, MAX_TREE_SIZE, "\\%s", share);
4411 rc = ops->tree_connect(xid, tcon->ses, tree, tcon, cifs_sb->local_nls);
4415 * If no dfs referrals were returned from link target, then just do a TREE_CONNECT
4416 * to it. Otherwise, cache the dfs referral and then mark current tcp ses for
4417 * reconnect so either the demultiplex thread or the echo worker will reconnect to
4418 * newly resolved target.
4420 if (dfs_cache_find(xid, tcon->ses, cifs_sb->local_nls, cifs_remap(cifs_sb), target,
4422 rc = ops->tree_connect(xid, tcon->ses, tree, tcon, cifs_sb->local_nls);
4425 rc = dfs_cache_noreq_update_tgthint(server->current_fullpath + 1, tit);
4427 rc = cifs_update_super_prepath(cifs_sb, prefix);
4429 /* Target is another dfs share */
4430 rc = update_server_fullpath(server, cifs_sb, target);
4431 dfs_cache_free_tgts(tl);
4435 list_replace_init(&ntl.tl_list, &tl->tl_list);
4437 dfs_cache_free_tgts(&ntl);
4449 static int tree_connect_dfs_target(const unsigned int xid, struct cifs_tcon *tcon,
4450 struct cifs_sb_info *cifs_sb, char *tree, bool islink,
4451 struct dfs_cache_tgt_list *tl)
4455 struct TCP_Server_Info *server = tcon->ses->server;
4458 rc = __tree_connect_dfs_target(xid, tcon, cifs_sb, tree, islink, tl);
4459 if (!rc || rc != -EREMOTE)
4461 } while (rc = -ELOOP, ++num_links < MAX_NESTED_LINKS);
4463 * If we couldn't tree connect to any targets from last referral path, then retry from
4464 * original referral path.
4466 if (rc && server->current_fullpath != server->origin_fullpath) {
4467 server->current_fullpath = server->origin_fullpath;
4468 cifs_reconnect(tcon->ses->server, true);
4471 dfs_cache_free_tgts(tl);
4475 int cifs_tree_connect(const unsigned int xid, struct cifs_tcon *tcon, const struct nls_table *nlsc)
4478 struct TCP_Server_Info *server = tcon->ses->server;
4479 const struct smb_version_operations *ops = server->ops;
4480 struct super_block *sb = NULL;
4481 struct cifs_sb_info *cifs_sb;
4482 struct dfs_cache_tgt_list tl = DFS_CACHE_TGT_LIST_INIT(tl);
4484 struct dfs_info3_param ref = {0};
4486 /* only send once per connect */
4487 spin_lock(&cifs_tcp_ses_lock);
4488 if (tcon->ses->status != CifsGood ||
4489 (tcon->status != TID_NEW &&
4490 tcon->status != TID_NEED_TCON)) {
4491 spin_unlock(&cifs_tcp_ses_lock);
4494 tcon->status = TID_IN_TCON;
4495 spin_unlock(&cifs_tcp_ses_lock);
4497 tree = kzalloc(MAX_TREE_SIZE, GFP_KERNEL);
4504 scnprintf(tree, MAX_TREE_SIZE, "\\\\%s\\IPC$", server->hostname);
4505 rc = ops->tree_connect(xid, tcon->ses, tree, tcon, nlsc);
4509 sb = cifs_get_tcp_super(server);
4512 cifs_dbg(VFS, "%s: could not find superblock: %d\n", __func__, rc);
4516 cifs_sb = CIFS_SB(sb);
4518 /* If it is not dfs or there was no cached dfs referral, then reconnect to same share */
4519 if (!server->current_fullpath ||
4520 dfs_cache_noreq_find(server->current_fullpath + 1, &ref, &tl)) {
4521 rc = ops->tree_connect(xid, tcon->ses, tcon->treeName, tcon, cifs_sb->local_nls);
4525 rc = tree_connect_dfs_target(xid, tcon, cifs_sb, tree, ref.server_type == DFS_TYPE_LINK,
4527 free_dfs_info_param(&ref);
4531 cifs_put_tcp_super(sb);
4534 spin_lock(&cifs_tcp_ses_lock);
4535 if (tcon->status == TID_IN_TCON)
4536 tcon->status = TID_NEED_TCON;
4537 spin_unlock(&cifs_tcp_ses_lock);
4539 spin_lock(&cifs_tcp_ses_lock);
4540 if (tcon->status == TID_IN_TCON)
4541 tcon->status = TID_GOOD;
4542 spin_unlock(&cifs_tcp_ses_lock);
4543 tcon->need_reconnect = false;
4549 int cifs_tree_connect(const unsigned int xid, struct cifs_tcon *tcon, const struct nls_table *nlsc)
4552 const struct smb_version_operations *ops = tcon->ses->server->ops;
4554 /* only send once per connect */
4555 spin_lock(&cifs_tcp_ses_lock);
4556 if (tcon->ses->status != CifsGood ||
4557 (tcon->status != TID_NEW &&
4558 tcon->status != TID_NEED_TCON)) {
4559 spin_unlock(&cifs_tcp_ses_lock);
4562 tcon->status = TID_IN_TCON;
4563 spin_unlock(&cifs_tcp_ses_lock);
4565 rc = ops->tree_connect(xid, tcon->ses, tcon->treeName, tcon, nlsc);
4567 spin_lock(&cifs_tcp_ses_lock);
4568 if (tcon->status == TID_IN_TCON)
4569 tcon->status = TID_NEED_TCON;
4570 spin_unlock(&cifs_tcp_ses_lock);
4572 spin_lock(&cifs_tcp_ses_lock);
4573 if (tcon->status == TID_IN_TCON)
4574 tcon->status = TID_GOOD;
4575 spin_unlock(&cifs_tcp_ses_lock);
4576 tcon->need_reconnect = false;