1 // SPDX-License-Identifier: LGPL-2.1
4 * Copyright (C) International Business Machines Corp., 2002,2011
5 * Author(s): Steve French (sfrench@us.ibm.com)
10 #include <linux/string.h>
11 #include <linux/sched/mm.h>
12 #include <linux/sched/signal.h>
13 #include <linux/list.h>
14 #include <linux/wait.h>
15 #include <linux/slab.h>
16 #include <linux/pagemap.h>
17 #include <linux/ctype.h>
18 #include <linux/utsname.h>
19 #include <linux/mempool.h>
20 #include <linux/delay.h>
21 #include <linux/completion.h>
22 #include <linux/kthread.h>
23 #include <linux/pagevec.h>
24 #include <linux/freezer.h>
25 #include <linux/namei.h>
26 #include <linux/uuid.h>
27 #include <linux/uaccess.h>
28 #include <asm/processor.h>
29 #include <linux/inet.h>
30 #include <linux/module.h>
31 #include <keys/user-type.h>
33 #include <linux/parser.h>
34 #include <linux/bvec.h>
37 #include "cifsproto.h"
38 #include "cifs_unicode.h"
39 #include "cifs_debug.h"
40 #include "cifs_fs_sb.h"
43 #include "rfc1002pdu.h"
45 #include "smb2proto.h"
46 #include "smbdirect.h"
47 #include "dns_resolve.h"
48 #ifdef CONFIG_CIFS_DFS_UPCALL
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
64 static int ip_connect(struct TCP_Server_Info *server);
65 static int generic_ip_connect(struct TCP_Server_Info *server);
66 static void tlink_rb_insert(struct rb_root *root, struct tcon_link *new_tlink);
67 static void cifs_prune_tlinks(struct work_struct *work);
70 * Resolve hostname and set ip addr in tcp ses. Useful for hostnames that may
71 * get their ip addresses changed at some point.
73 * This should be called with server->srv_mutex held.
75 static int reconn_set_ipaddr_from_hostname(struct TCP_Server_Info *server)
79 char *unc, *ipaddr = NULL;
81 unsigned long ttl = SMB_DNS_RESOLVE_INTERVAL_DEFAULT;
83 if (!server->hostname)
86 len = strlen(server->hostname) + 3;
88 unc = kmalloc(len, GFP_KERNEL);
90 cifs_dbg(FYI, "%s: failed to create UNC path\n", __func__);
93 scnprintf(unc, len, "\\\\%s", server->hostname);
95 rc = dns_resolve_server_name_to_ip(unc, &ipaddr, &expiry);
99 cifs_dbg(FYI, "%s: failed to resolve server part of %s to IP: %d\n",
100 __func__, server->hostname, rc);
101 goto requeue_resolve;
104 spin_lock(&cifs_tcp_ses_lock);
105 rc = cifs_convert_address((struct sockaddr *)&server->dstaddr, ipaddr,
107 spin_unlock(&cifs_tcp_ses_lock);
110 /* rc == 1 means success here */
112 now = ktime_get_real_seconds();
113 if (expiry && expiry > now)
115 * To make sure we don't use the cached entry, retry 1s
118 ttl = (expiry - now + 1);
123 cifs_dbg(FYI, "%s: next dns resolution scheduled for %lu seconds in the future\n",
125 mod_delayed_work(cifsiod_wq, &server->resolve, (ttl * HZ));
131 static void cifs_resolve_server(struct work_struct *work)
134 struct TCP_Server_Info *server = container_of(work,
135 struct TCP_Server_Info, resolve.work);
137 mutex_lock(&server->srv_mutex);
140 * Resolve the hostname again to make sure that IP address is up-to-date.
142 rc = reconn_set_ipaddr_from_hostname(server);
144 cifs_dbg(FYI, "%s: failed to resolve hostname: %d\n",
148 mutex_unlock(&server->srv_mutex);
151 #ifdef CONFIG_CIFS_DFS_UPCALL
152 /* These functions must be called with server->srv_mutex held */
153 static void reconn_set_next_dfs_target(struct TCP_Server_Info *server,
154 struct cifs_sb_info *cifs_sb,
155 struct dfs_cache_tgt_list *tgt_list,
156 struct dfs_cache_tgt_iterator **tgt_it)
161 if (!cifs_sb || !cifs_sb->origin_fullpath)
165 *tgt_it = dfs_cache_get_tgt_iterator(tgt_list);
167 *tgt_it = dfs_cache_get_next_tgt(tgt_list, *tgt_it);
169 *tgt_it = dfs_cache_get_tgt_iterator(tgt_list);
172 cifs_dbg(FYI, "%s: UNC: %s\n", __func__, cifs_sb->origin_fullpath);
174 name = dfs_cache_get_tgt_name(*tgt_it);
176 kfree(server->hostname);
178 server->hostname = extract_hostname(name);
179 if (IS_ERR(server->hostname)) {
181 "%s: failed to extract hostname from target: %ld\n",
182 __func__, PTR_ERR(server->hostname));
186 rc = reconn_set_ipaddr_from_hostname(server);
188 cifs_dbg(FYI, "%s: failed to resolve hostname: %d\n",
193 static inline int reconn_setup_dfs_targets(struct cifs_sb_info *cifs_sb,
194 struct dfs_cache_tgt_list *tl)
196 if (!cifs_sb->origin_fullpath)
198 return dfs_cache_noreq_find(cifs_sb->origin_fullpath + 1, NULL, tl);
203 * Mark all sessions and tcons for reconnect.
205 * @server needs to be previously set to CifsNeedReconnect.
207 static void cifs_mark_tcp_ses_conns_for_reconnect(struct TCP_Server_Info *server)
209 struct list_head *tmp, *tmp2;
210 struct cifs_ses *ses;
211 struct cifs_tcon *tcon;
212 struct mid_q_entry *mid_entry;
213 struct list_head retry_list;
216 server->max_read = 0;
218 cifs_dbg(FYI, "Mark tcp session as need reconnect\n");
219 trace_smb3_reconnect(server->CurrentMid, server->conn_id, server->hostname);
221 * before reconnecting the tcp session, mark the smb session (uid) and the tid bad so they
222 * are not used until reconnected.
224 cifs_dbg(FYI, "%s: marking sessions and tcons for reconnect\n", __func__);
225 spin_lock(&cifs_tcp_ses_lock);
226 list_for_each(tmp, &server->smb_ses_list) {
227 ses = list_entry(tmp, struct cifs_ses, smb_ses_list);
228 ses->need_reconnect = true;
229 list_for_each(tmp2, &ses->tcon_list) {
230 tcon = list_entry(tmp2, struct cifs_tcon, tcon_list);
231 tcon->need_reconnect = true;
234 ses->tcon_ipc->need_reconnect = true;
236 spin_unlock(&cifs_tcp_ses_lock);
238 /* do not want to be sending data on a socket we are freeing */
239 cifs_dbg(FYI, "%s: tearing down socket\n", __func__);
240 mutex_lock(&server->srv_mutex);
241 if (server->ssocket) {
242 cifs_dbg(FYI, "State: 0x%x Flags: 0x%lx\n", server->ssocket->state,
243 server->ssocket->flags);
244 kernel_sock_shutdown(server->ssocket, SHUT_WR);
245 cifs_dbg(FYI, "Post shutdown state: 0x%x Flags: 0x%lx\n", server->ssocket->state,
246 server->ssocket->flags);
247 sock_release(server->ssocket);
248 server->ssocket = NULL;
250 server->sequence_number = 0;
251 server->session_estab = false;
252 kfree(server->session_key.response);
253 server->session_key.response = NULL;
254 server->session_key.len = 0;
255 server->lstrp = jiffies;
257 /* mark submitted MIDs for retry and issue callback */
258 INIT_LIST_HEAD(&retry_list);
259 cifs_dbg(FYI, "%s: moving mids to private list\n", __func__);
260 spin_lock(&GlobalMid_Lock);
261 list_for_each_safe(tmp, tmp2, &server->pending_mid_q) {
262 mid_entry = list_entry(tmp, struct mid_q_entry, qhead);
263 kref_get(&mid_entry->refcount);
264 if (mid_entry->mid_state == MID_REQUEST_SUBMITTED)
265 mid_entry->mid_state = MID_RETRY_NEEDED;
266 list_move(&mid_entry->qhead, &retry_list);
267 mid_entry->mid_flags |= MID_DELETED;
269 spin_unlock(&GlobalMid_Lock);
270 mutex_unlock(&server->srv_mutex);
272 cifs_dbg(FYI, "%s: issuing mid callbacks\n", __func__);
273 list_for_each_safe(tmp, tmp2, &retry_list) {
274 mid_entry = list_entry(tmp, struct mid_q_entry, qhead);
275 list_del_init(&mid_entry->qhead);
276 mid_entry->callback(mid_entry);
277 cifs_mid_q_entry_release(mid_entry);
280 if (cifs_rdma_enabled(server)) {
281 mutex_lock(&server->srv_mutex);
282 smbd_destroy(server);
283 mutex_unlock(&server->srv_mutex);
288 * cifs tcp session reconnection
290 * mark tcp session as reconnecting so temporarily locked
291 * mark all smb sessions as reconnecting for tcp session
292 * reconnect tcp session
293 * wake up waiters on reconnection? - (not needed currently)
296 cifs_reconnect(struct TCP_Server_Info *server)
299 #ifdef CONFIG_CIFS_DFS_UPCALL
300 struct super_block *sb = NULL;
301 struct cifs_sb_info *cifs_sb = NULL;
302 struct dfs_cache_tgt_list tgt_list = DFS_CACHE_TGT_LIST_INIT(tgt_list);
303 struct dfs_cache_tgt_iterator *tgt_it = NULL;
306 spin_lock(&GlobalMid_Lock);
307 server->nr_targets = 1;
308 #ifdef CONFIG_CIFS_DFS_UPCALL
309 spin_unlock(&GlobalMid_Lock);
310 sb = cifs_get_tcp_super(server);
313 cifs_dbg(FYI, "%s: will not do DFS failover: rc = %d\n",
317 cifs_sb = CIFS_SB(sb);
318 rc = reconn_setup_dfs_targets(cifs_sb, &tgt_list);
321 if (rc != -EOPNOTSUPP) {
322 cifs_server_dbg(VFS, "%s: no target servers for DFS failover\n",
326 server->nr_targets = dfs_cache_get_nr_tgts(&tgt_list);
329 cifs_dbg(FYI, "%s: will retry %d target(s)\n", __func__,
331 spin_lock(&GlobalMid_Lock);
333 if (server->tcpStatus == CifsExiting) {
334 /* the demux thread will exit normally next time through the loop */
335 spin_unlock(&GlobalMid_Lock);
336 #ifdef CONFIG_CIFS_DFS_UPCALL
337 dfs_cache_free_tgts(&tgt_list);
338 cifs_put_tcp_super(sb);
340 wake_up(&server->response_q);
343 server->tcpStatus = CifsNeedReconnect;
344 spin_unlock(&GlobalMid_Lock);
346 cifs_mark_tcp_ses_conns_for_reconnect(server);
351 mutex_lock(&server->srv_mutex);
354 if (!cifs_swn_set_server_dstaddr(server)) {
355 #ifdef CONFIG_CIFS_DFS_UPCALL
356 if (cifs_sb && cifs_sb->origin_fullpath)
358 * Set up next DFS target server (if any) for reconnect. If DFS
359 * feature is disabled, then we will retry last server we
360 * connected to before.
362 reconn_set_next_dfs_target(server, cifs_sb, &tgt_list, &tgt_it);
366 * Resolve the hostname again to make sure that IP address is up-to-date.
368 rc = reconn_set_ipaddr_from_hostname(server);
370 cifs_dbg(FYI, "%s: failed to resolve hostname: %d\n",
374 #ifdef CONFIG_CIFS_DFS_UPCALL
381 if (cifs_rdma_enabled(server))
382 rc = smbd_reconnect(server);
384 rc = generic_ip_connect(server);
386 cifs_dbg(FYI, "reconnect error %d\n", rc);
387 mutex_unlock(&server->srv_mutex);
390 atomic_inc(&tcpSesReconnectCount);
391 set_credits(server, 1);
392 spin_lock(&GlobalMid_Lock);
393 if (server->tcpStatus != CifsExiting)
394 server->tcpStatus = CifsNeedNegotiate;
395 spin_unlock(&GlobalMid_Lock);
396 cifs_swn_reset_server_dstaddr(server);
397 mutex_unlock(&server->srv_mutex);
399 } while (server->tcpStatus == CifsNeedReconnect);
401 #ifdef CONFIG_CIFS_DFS_UPCALL
403 rc = dfs_cache_noreq_update_tgthint(cifs_sb->origin_fullpath + 1,
406 cifs_server_dbg(VFS, "%s: failed to update DFS target hint: rc = %d\n",
409 dfs_cache_free_tgts(&tgt_list);
412 cifs_put_tcp_super(sb);
414 if (server->tcpStatus == CifsNeedNegotiate)
415 mod_delayed_work(cifsiod_wq, &server->echo, 0);
417 wake_up(&server->response_q);
422 cifs_echo_request(struct work_struct *work)
425 struct TCP_Server_Info *server = container_of(work,
426 struct TCP_Server_Info, echo.work);
429 * We cannot send an echo if it is disabled.
430 * Also, no need to ping if we got a response recently.
433 if (server->tcpStatus == CifsNeedReconnect ||
434 server->tcpStatus == CifsExiting ||
435 server->tcpStatus == CifsNew ||
436 (server->ops->can_echo && !server->ops->can_echo(server)) ||
437 time_before(jiffies, server->lstrp + server->echo_interval - HZ))
440 rc = server->ops->echo ? server->ops->echo(server) : -ENOSYS;
442 cifs_dbg(FYI, "Unable to send echo request to server: %s\n",
445 /* Check witness registrations */
449 queue_delayed_work(cifsiod_wq, &server->echo, server->echo_interval);
453 allocate_buffers(struct TCP_Server_Info *server)
455 if (!server->bigbuf) {
456 server->bigbuf = (char *)cifs_buf_get();
457 if (!server->bigbuf) {
458 cifs_server_dbg(VFS, "No memory for large SMB response\n");
460 /* retry will check if exiting */
463 } else if (server->large_buf) {
464 /* we are reusing a dirty large buf, clear its start */
465 memset(server->bigbuf, 0, HEADER_SIZE(server));
468 if (!server->smallbuf) {
469 server->smallbuf = (char *)cifs_small_buf_get();
470 if (!server->smallbuf) {
471 cifs_server_dbg(VFS, "No memory for SMB response\n");
473 /* retry will check if exiting */
476 /* beginning of smb buffer is cleared in our buf_get */
478 /* if existing small buf clear beginning */
479 memset(server->smallbuf, 0, HEADER_SIZE(server));
486 server_unresponsive(struct TCP_Server_Info *server)
489 * We need to wait 3 echo intervals to make sure we handle such
491 * 1s client sends a normal SMB request
492 * 2s client gets a response
493 * 30s echo workqueue job pops, and decides we got a response recently
494 * and don't need to send another
496 * 65s kernel_recvmsg times out, and we see that we haven't gotten
497 * a response in >60s.
499 if ((server->tcpStatus == CifsGood ||
500 server->tcpStatus == CifsNeedNegotiate) &&
501 (!server->ops->can_echo || server->ops->can_echo(server)) &&
502 time_after(jiffies, server->lstrp + 3 * server->echo_interval)) {
503 cifs_server_dbg(VFS, "has not responded in %lu seconds. Reconnecting...\n",
504 (3 * server->echo_interval) / HZ);
505 cifs_reconnect(server);
513 zero_credits(struct TCP_Server_Info *server)
517 spin_lock(&server->req_lock);
518 val = server->credits + server->echo_credits + server->oplock_credits;
519 if (server->in_flight == 0 && val == 0) {
520 spin_unlock(&server->req_lock);
523 spin_unlock(&server->req_lock);
528 cifs_readv_from_socket(struct TCP_Server_Info *server, struct msghdr *smb_msg)
533 smb_msg->msg_control = NULL;
534 smb_msg->msg_controllen = 0;
536 for (total_read = 0; msg_data_left(smb_msg); total_read += length) {
539 /* reconnect if no credits and no requests in flight */
540 if (zero_credits(server)) {
541 cifs_reconnect(server);
542 return -ECONNABORTED;
545 if (server_unresponsive(server))
546 return -ECONNABORTED;
547 if (cifs_rdma_enabled(server) && server->smbd_conn)
548 length = smbd_recv(server->smbd_conn, smb_msg);
550 length = sock_recvmsg(server->ssocket, smb_msg, 0);
552 if (server->tcpStatus == CifsExiting)
555 if (server->tcpStatus == CifsNeedReconnect) {
556 cifs_reconnect(server);
557 return -ECONNABORTED;
560 if (length == -ERESTARTSYS ||
564 * Minimum sleep to prevent looping, allowing socket
565 * to clear and app threads to set tcpStatus
566 * CifsNeedReconnect if server hung.
568 usleep_range(1000, 2000);
574 cifs_dbg(FYI, "Received no data or error: %d\n", length);
575 cifs_reconnect(server);
576 return -ECONNABORTED;
583 cifs_read_from_socket(struct TCP_Server_Info *server, char *buf,
584 unsigned int to_read)
586 struct msghdr smb_msg;
587 struct kvec iov = {.iov_base = buf, .iov_len = to_read};
588 iov_iter_kvec(&smb_msg.msg_iter, READ, &iov, 1, to_read);
590 return cifs_readv_from_socket(server, &smb_msg);
594 cifs_discard_from_socket(struct TCP_Server_Info *server, size_t to_read)
596 struct msghdr smb_msg;
599 * iov_iter_discard already sets smb_msg.type and count and iov_offset
600 * and cifs_readv_from_socket sets msg_control and msg_controllen
601 * so little to initialize in struct msghdr
603 smb_msg.msg_name = NULL;
604 smb_msg.msg_namelen = 0;
605 iov_iter_discard(&smb_msg.msg_iter, READ, to_read);
607 return cifs_readv_from_socket(server, &smb_msg);
611 cifs_read_page_from_socket(struct TCP_Server_Info *server, struct page *page,
612 unsigned int page_offset, unsigned int to_read)
614 struct msghdr smb_msg;
615 struct bio_vec bv = {
616 .bv_page = page, .bv_len = to_read, .bv_offset = page_offset};
617 iov_iter_bvec(&smb_msg.msg_iter, READ, &bv, 1, to_read);
618 return cifs_readv_from_socket(server, &smb_msg);
622 is_smb_response(struct TCP_Server_Info *server, unsigned char type)
625 * The first byte big endian of the length field,
626 * is actually not part of the length but the type
627 * with the most common, zero, as regular data.
630 case RFC1002_SESSION_MESSAGE:
631 /* Regular SMB response */
633 case RFC1002_SESSION_KEEP_ALIVE:
634 cifs_dbg(FYI, "RFC 1002 session keep alive\n");
636 case RFC1002_POSITIVE_SESSION_RESPONSE:
637 cifs_dbg(FYI, "RFC 1002 positive session response\n");
639 case RFC1002_NEGATIVE_SESSION_RESPONSE:
641 * We get this from Windows 98 instead of an error on
642 * SMB negprot response.
644 cifs_dbg(FYI, "RFC 1002 negative session response\n");
645 /* give server a second to clean up */
648 * Always try 445 first on reconnect since we get NACK
649 * on some if we ever connected to port 139 (the NACK
650 * is since we do not begin with RFC1001 session
653 cifs_set_port((struct sockaddr *)&server->dstaddr, CIFS_PORT);
654 cifs_reconnect(server);
657 cifs_server_dbg(VFS, "RFC 1002 unknown response type 0x%x\n", type);
658 cifs_reconnect(server);
665 dequeue_mid(struct mid_q_entry *mid, bool malformed)
667 #ifdef CONFIG_CIFS_STATS2
668 mid->when_received = jiffies;
670 spin_lock(&GlobalMid_Lock);
672 mid->mid_state = MID_RESPONSE_RECEIVED;
674 mid->mid_state = MID_RESPONSE_MALFORMED;
676 * Trying to handle/dequeue a mid after the send_recv()
677 * function has finished processing it is a bug.
679 if (mid->mid_flags & MID_DELETED)
680 pr_warn_once("trying to dequeue a deleted mid\n");
682 list_del_init(&mid->qhead);
683 mid->mid_flags |= MID_DELETED;
685 spin_unlock(&GlobalMid_Lock);
689 smb2_get_credits_from_hdr(char *buffer, struct TCP_Server_Info *server)
691 struct smb2_hdr *shdr = (struct smb2_hdr *)buffer;
694 * SMB1 does not use credits.
696 if (server->vals->header_preamble_size)
699 return le16_to_cpu(shdr->CreditRequest);
703 handle_mid(struct mid_q_entry *mid, struct TCP_Server_Info *server,
704 char *buf, int malformed)
706 if (server->ops->check_trans2 &&
707 server->ops->check_trans2(mid, server, buf, malformed))
709 mid->credits_received = smb2_get_credits_from_hdr(buf, server);
711 mid->large_buf = server->large_buf;
712 /* Was previous buf put in mpx struct for multi-rsp? */
713 if (!mid->multiRsp) {
714 /* smb buffer will be freed by user thread */
715 if (server->large_buf)
716 server->bigbuf = NULL;
718 server->smallbuf = NULL;
720 dequeue_mid(mid, malformed);
723 static void clean_demultiplex_info(struct TCP_Server_Info *server)
727 /* take it off the list, if it's not already */
728 spin_lock(&cifs_tcp_ses_lock);
729 list_del_init(&server->tcp_ses_list);
730 spin_unlock(&cifs_tcp_ses_lock);
732 cancel_delayed_work_sync(&server->echo);
733 cancel_delayed_work_sync(&server->resolve);
735 spin_lock(&GlobalMid_Lock);
736 server->tcpStatus = CifsExiting;
737 spin_unlock(&GlobalMid_Lock);
738 wake_up_all(&server->response_q);
740 /* check if we have blocked requests that need to free */
741 spin_lock(&server->req_lock);
742 if (server->credits <= 0)
744 spin_unlock(&server->req_lock);
746 * Although there should not be any requests blocked on this queue it
747 * can not hurt to be paranoid and try to wake up requests that may
748 * haven been blocked when more than 50 at time were on the wire to the
749 * same server - they now will see the session is in exit state and get
750 * out of SendReceive.
752 wake_up_all(&server->request_q);
753 /* give those requests time to exit */
755 if (cifs_rdma_enabled(server))
756 smbd_destroy(server);
757 if (server->ssocket) {
758 sock_release(server->ssocket);
759 server->ssocket = NULL;
762 if (!list_empty(&server->pending_mid_q)) {
763 struct list_head dispose_list;
764 struct mid_q_entry *mid_entry;
765 struct list_head *tmp, *tmp2;
767 INIT_LIST_HEAD(&dispose_list);
768 spin_lock(&GlobalMid_Lock);
769 list_for_each_safe(tmp, tmp2, &server->pending_mid_q) {
770 mid_entry = list_entry(tmp, struct mid_q_entry, qhead);
771 cifs_dbg(FYI, "Clearing mid %llu\n", mid_entry->mid);
772 kref_get(&mid_entry->refcount);
773 mid_entry->mid_state = MID_SHUTDOWN;
774 list_move(&mid_entry->qhead, &dispose_list);
775 mid_entry->mid_flags |= MID_DELETED;
777 spin_unlock(&GlobalMid_Lock);
779 /* now walk dispose list and issue callbacks */
780 list_for_each_safe(tmp, tmp2, &dispose_list) {
781 mid_entry = list_entry(tmp, struct mid_q_entry, qhead);
782 cifs_dbg(FYI, "Callback mid %llu\n", mid_entry->mid);
783 list_del_init(&mid_entry->qhead);
784 mid_entry->callback(mid_entry);
785 cifs_mid_q_entry_release(mid_entry);
787 /* 1/8th of sec is more than enough time for them to exit */
791 if (!list_empty(&server->pending_mid_q)) {
793 * mpx threads have not exited yet give them at least the smb
794 * send timeout time for long ops.
796 * Due to delays on oplock break requests, we need to wait at
797 * least 45 seconds before giving up on a request getting a
798 * response and going ahead and killing cifsd.
800 cifs_dbg(FYI, "Wait for exit from demultiplex thread\n");
803 * If threads still have not exited they are probably never
804 * coming home not much else we can do but free the memory.
810 length = atomic_dec_return(&tcpSesAllocCount);
812 mempool_resize(cifs_req_poolp, length + cifs_min_rcv);
816 standard_receive3(struct TCP_Server_Info *server, struct mid_q_entry *mid)
819 char *buf = server->smallbuf;
820 unsigned int pdu_length = server->pdu_size;
822 /* make sure this will fit in a large buffer */
823 if (pdu_length > CIFSMaxBufSize + MAX_HEADER_SIZE(server) -
824 server->vals->header_preamble_size) {
825 cifs_server_dbg(VFS, "SMB response too long (%u bytes)\n", pdu_length);
826 cifs_reconnect(server);
827 return -ECONNABORTED;
830 /* switch to large buffer if too big for a small one */
831 if (pdu_length > MAX_CIFS_SMALL_BUFFER_SIZE - 4) {
832 server->large_buf = true;
833 memcpy(server->bigbuf, buf, server->total_read);
834 buf = server->bigbuf;
837 /* now read the rest */
838 length = cifs_read_from_socket(server, buf + HEADER_SIZE(server) - 1,
839 pdu_length - HEADER_SIZE(server) + 1
840 + server->vals->header_preamble_size);
844 server->total_read += length;
846 dump_smb(buf, server->total_read);
848 return cifs_handle_standard(server, mid);
852 cifs_handle_standard(struct TCP_Server_Info *server, struct mid_q_entry *mid)
854 char *buf = server->large_buf ? server->bigbuf : server->smallbuf;
858 * We know that we received enough to get to the MID as we
859 * checked the pdu_length earlier. Now check to see
860 * if the rest of the header is OK. We borrow the length
861 * var for the rest of the loop to avoid a new stack var.
863 * 48 bytes is enough to display the header and a little bit
864 * into the payload for debugging purposes.
866 length = server->ops->check_message(buf, server->total_read, server);
868 cifs_dump_mem("Bad SMB: ", buf,
869 min_t(unsigned int, server->total_read, 48));
871 if (server->ops->is_session_expired &&
872 server->ops->is_session_expired(buf)) {
873 cifs_reconnect(server);
877 if (server->ops->is_status_pending &&
878 server->ops->is_status_pending(buf, server))
884 handle_mid(mid, server, buf, length);
889 smb2_add_credits_from_hdr(char *buffer, struct TCP_Server_Info *server)
891 struct smb2_hdr *shdr = (struct smb2_hdr *)buffer;
892 int scredits, in_flight;
895 * SMB1 does not use credits.
897 if (server->vals->header_preamble_size)
900 if (shdr->CreditRequest) {
901 spin_lock(&server->req_lock);
902 server->credits += le16_to_cpu(shdr->CreditRequest);
903 scredits = server->credits;
904 in_flight = server->in_flight;
905 spin_unlock(&server->req_lock);
906 wake_up(&server->request_q);
908 trace_smb3_add_credits(server->CurrentMid,
909 server->conn_id, server->hostname, scredits,
910 le16_to_cpu(shdr->CreditRequest), in_flight);
911 cifs_server_dbg(FYI, "%s: added %u credits total=%d\n",
912 __func__, le16_to_cpu(shdr->CreditRequest),
919 cifs_demultiplex_thread(void *p)
921 int i, num_mids, length;
922 struct TCP_Server_Info *server = p;
923 unsigned int pdu_length;
924 unsigned int next_offset;
926 struct task_struct *task_to_wake = NULL;
927 struct mid_q_entry *mids[MAX_COMPOUND];
928 char *bufs[MAX_COMPOUND];
929 unsigned int noreclaim_flag, num_io_timeout = 0;
931 noreclaim_flag = memalloc_noreclaim_save();
932 cifs_dbg(FYI, "Demultiplex PID: %d\n", task_pid_nr(current));
934 length = atomic_inc_return(&tcpSesAllocCount);
936 mempool_resize(cifs_req_poolp, length + cifs_min_rcv);
939 allow_kernel_signal(SIGKILL);
940 while (server->tcpStatus != CifsExiting) {
944 if (!allocate_buffers(server))
947 server->large_buf = false;
948 buf = server->smallbuf;
949 pdu_length = 4; /* enough to get RFC1001 header */
951 length = cifs_read_from_socket(server, buf, pdu_length);
955 if (server->vals->header_preamble_size == 0)
956 server->total_read = 0;
958 server->total_read = length;
961 * The right amount was read from socket - 4 bytes,
962 * so we can now interpret the length field.
964 pdu_length = get_rfc1002_length(buf);
966 cifs_dbg(FYI, "RFC1002 header 0x%x\n", pdu_length);
967 if (!is_smb_response(server, buf[0]))
970 server->pdu_size = pdu_length;
972 /* make sure we have enough to get to the MID */
973 if (server->pdu_size < HEADER_SIZE(server) - 1 -
974 server->vals->header_preamble_size) {
975 cifs_server_dbg(VFS, "SMB response too short (%u bytes)\n",
977 cifs_reconnect(server);
981 /* read down to the MID */
982 length = cifs_read_from_socket(server,
983 buf + server->vals->header_preamble_size,
984 HEADER_SIZE(server) - 1
985 - server->vals->header_preamble_size);
988 server->total_read += length;
990 if (server->ops->next_header) {
991 next_offset = server->ops->next_header(buf);
993 server->pdu_size = next_offset;
996 memset(mids, 0, sizeof(mids));
997 memset(bufs, 0, sizeof(bufs));
1000 if (server->ops->is_transform_hdr &&
1001 server->ops->receive_transform &&
1002 server->ops->is_transform_hdr(buf)) {
1003 length = server->ops->receive_transform(server,
1008 mids[0] = server->ops->find_mid(server, buf);
1012 if (!mids[0] || !mids[0]->receive)
1013 length = standard_receive3(server, mids[0]);
1015 length = mids[0]->receive(server, mids[0]);
1019 for (i = 0; i < num_mids; i++)
1021 cifs_mid_q_entry_release(mids[i]);
1025 if (server->ops->is_status_io_timeout &&
1026 server->ops->is_status_io_timeout(buf)) {
1028 if (num_io_timeout > NUM_STATUS_IO_TIMEOUT) {
1029 cifs_reconnect(server);
1035 server->lstrp = jiffies;
1037 for (i = 0; i < num_mids; i++) {
1038 if (mids[i] != NULL) {
1039 mids[i]->resp_buf_size = server->pdu_size;
1041 if (bufs[i] && server->ops->is_network_name_deleted)
1042 server->ops->is_network_name_deleted(bufs[i],
1045 if (!mids[i]->multiRsp || mids[i]->multiEnd)
1046 mids[i]->callback(mids[i]);
1048 cifs_mid_q_entry_release(mids[i]);
1049 } else if (server->ops->is_oplock_break &&
1050 server->ops->is_oplock_break(bufs[i],
1052 smb2_add_credits_from_hdr(bufs[i], server);
1053 cifs_dbg(FYI, "Received oplock break\n");
1055 cifs_server_dbg(VFS, "No task to wake, unknown frame received! NumMids %d\n",
1056 atomic_read(&midCount));
1057 cifs_dump_mem("Received Data is: ", bufs[i],
1058 HEADER_SIZE(server));
1059 smb2_add_credits_from_hdr(bufs[i], server);
1060 #ifdef CONFIG_CIFS_DEBUG2
1061 if (server->ops->dump_detail)
1062 server->ops->dump_detail(bufs[i],
1064 cifs_dump_mids(server);
1065 #endif /* CIFS_DEBUG2 */
1069 if (pdu_length > server->pdu_size) {
1070 if (!allocate_buffers(server))
1072 pdu_length -= server->pdu_size;
1073 server->total_read = 0;
1074 server->large_buf = false;
1075 buf = server->smallbuf;
1078 } /* end while !EXITING */
1080 /* buffer usually freed in free_mid - need to free it here on exit */
1081 cifs_buf_release(server->bigbuf);
1082 if (server->smallbuf) /* no sense logging a debug message if NULL */
1083 cifs_small_buf_release(server->smallbuf);
1085 task_to_wake = xchg(&server->tsk, NULL);
1086 clean_demultiplex_info(server);
1088 /* if server->tsk was NULL then wait for a signal before exiting */
1089 if (!task_to_wake) {
1090 set_current_state(TASK_INTERRUPTIBLE);
1091 while (!signal_pending(current)) {
1093 set_current_state(TASK_INTERRUPTIBLE);
1095 set_current_state(TASK_RUNNING);
1098 memalloc_noreclaim_restore(noreclaim_flag);
1099 module_put_and_exit(0);
1103 * Returns true if srcaddr isn't specified and rhs isn't specified, or
1104 * if srcaddr is specified and matches the IP address of the rhs argument
1107 cifs_match_ipaddr(struct sockaddr *srcaddr, struct sockaddr *rhs)
1109 switch (srcaddr->sa_family) {
1111 return (rhs->sa_family == AF_UNSPEC);
1113 struct sockaddr_in *saddr4 = (struct sockaddr_in *)srcaddr;
1114 struct sockaddr_in *vaddr4 = (struct sockaddr_in *)rhs;
1115 return (saddr4->sin_addr.s_addr == vaddr4->sin_addr.s_addr);
1118 struct sockaddr_in6 *saddr6 = (struct sockaddr_in6 *)srcaddr;
1119 struct sockaddr_in6 *vaddr6 = (struct sockaddr_in6 *)rhs;
1120 return ipv6_addr_equal(&saddr6->sin6_addr, &vaddr6->sin6_addr);
1124 return false; /* don't expect to be here */
1129 * If no port is specified in addr structure, we try to match with 445 port
1130 * and if it fails - with 139 ports. It should be called only if address
1131 * families of server and addr are equal.
1134 match_port(struct TCP_Server_Info *server, struct sockaddr *addr)
1136 __be16 port, *sport;
1138 /* SMBDirect manages its own ports, don't match it here */
1142 switch (addr->sa_family) {
1144 sport = &((struct sockaddr_in *) &server->dstaddr)->sin_port;
1145 port = ((struct sockaddr_in *) addr)->sin_port;
1148 sport = &((struct sockaddr_in6 *) &server->dstaddr)->sin6_port;
1149 port = ((struct sockaddr_in6 *) addr)->sin6_port;
1157 port = htons(CIFS_PORT);
1161 port = htons(RFC1001_PORT);
1164 return port == *sport;
1168 match_address(struct TCP_Server_Info *server, struct sockaddr *addr,
1169 struct sockaddr *srcaddr)
1171 switch (addr->sa_family) {
1173 struct sockaddr_in *addr4 = (struct sockaddr_in *)addr;
1174 struct sockaddr_in *srv_addr4 =
1175 (struct sockaddr_in *)&server->dstaddr;
1177 if (addr4->sin_addr.s_addr != srv_addr4->sin_addr.s_addr)
1182 struct sockaddr_in6 *addr6 = (struct sockaddr_in6 *)addr;
1183 struct sockaddr_in6 *srv_addr6 =
1184 (struct sockaddr_in6 *)&server->dstaddr;
1186 if (!ipv6_addr_equal(&addr6->sin6_addr,
1187 &srv_addr6->sin6_addr))
1189 if (addr6->sin6_scope_id != srv_addr6->sin6_scope_id)
1195 return false; /* don't expect to be here */
1198 if (!cifs_match_ipaddr(srcaddr, (struct sockaddr *)&server->srcaddr))
1205 match_security(struct TCP_Server_Info *server, struct smb3_fs_context *ctx)
1208 * The select_sectype function should either return the ctx->sectype
1209 * that was specified, or "Unspecified" if that sectype was not
1210 * compatible with the given NEGOTIATE request.
1212 if (server->ops->select_sectype(server, ctx->sectype)
1217 * Now check if signing mode is acceptable. No need to check
1218 * global_secflags at this point since if MUST_SIGN is set then
1219 * the server->sign had better be too.
1221 if (ctx->sign && !server->sign)
1227 static int match_server(struct TCP_Server_Info *server, struct smb3_fs_context *ctx)
1229 struct sockaddr *addr = (struct sockaddr *)&ctx->dstaddr;
1231 if (ctx->nosharesock) {
1232 server->nosharesock = true;
1236 /* this server does not share socket */
1237 if (server->nosharesock)
1240 /* If multidialect negotiation see if existing sessions match one */
1241 if (strcmp(ctx->vals->version_string, SMB3ANY_VERSION_STRING) == 0) {
1242 if (server->vals->protocol_id < SMB30_PROT_ID)
1244 } else if (strcmp(ctx->vals->version_string,
1245 SMBDEFAULT_VERSION_STRING) == 0) {
1246 if (server->vals->protocol_id < SMB21_PROT_ID)
1248 } else if ((server->vals != ctx->vals) || (server->ops != ctx->ops))
1251 if (!net_eq(cifs_net_ns(server), current->nsproxy->net_ns))
1254 if (strcasecmp(server->hostname, ctx->server_hostname))
1257 if (!match_address(server, addr,
1258 (struct sockaddr *)&ctx->srcaddr))
1261 if (!match_port(server, addr))
1264 if (!match_security(server, ctx))
1267 if (server->echo_interval != ctx->echo_interval * HZ)
1270 if (server->rdma != ctx->rdma)
1273 if (server->ignore_signature != ctx->ignore_signature)
1276 if (server->min_offload != ctx->min_offload)
1282 struct TCP_Server_Info *
1283 cifs_find_tcp_session(struct smb3_fs_context *ctx)
1285 struct TCP_Server_Info *server;
1287 spin_lock(&cifs_tcp_ses_lock);
1288 list_for_each_entry(server, &cifs_tcp_ses_list, tcp_ses_list) {
1289 #ifdef CONFIG_CIFS_DFS_UPCALL
1291 * DFS failover implementation in cifs_reconnect() requires unique tcp sessions for
1292 * DFS connections to do failover properly, so avoid sharing them with regular
1293 * shares or even links that may connect to same server but having completely
1294 * different failover targets.
1296 if (server->is_dfs_conn)
1300 * Skip ses channels since they're only handled in lower layers
1301 * (e.g. cifs_send_recv).
1303 if (server->is_channel || !match_server(server, ctx))
1306 ++server->srv_count;
1307 spin_unlock(&cifs_tcp_ses_lock);
1308 cifs_dbg(FYI, "Existing tcp session with server found\n");
1311 spin_unlock(&cifs_tcp_ses_lock);
1316 cifs_put_tcp_session(struct TCP_Server_Info *server, int from_reconnect)
1318 struct task_struct *task;
1320 spin_lock(&cifs_tcp_ses_lock);
1321 if (--server->srv_count > 0) {
1322 spin_unlock(&cifs_tcp_ses_lock);
1326 /* srv_count can never go negative */
1327 WARN_ON(server->srv_count < 0);
1329 put_net(cifs_net_ns(server));
1331 list_del_init(&server->tcp_ses_list);
1332 spin_unlock(&cifs_tcp_ses_lock);
1334 cancel_delayed_work_sync(&server->echo);
1335 cancel_delayed_work_sync(&server->resolve);
1339 * Avoid deadlock here: reconnect work calls
1340 * cifs_put_tcp_session() at its end. Need to be sure
1341 * that reconnect work does nothing with server pointer after
1344 cancel_delayed_work(&server->reconnect);
1346 cancel_delayed_work_sync(&server->reconnect);
1348 spin_lock(&GlobalMid_Lock);
1349 server->tcpStatus = CifsExiting;
1350 spin_unlock(&GlobalMid_Lock);
1352 cifs_crypto_secmech_release(server);
1353 cifs_fscache_release_client_cookie(server);
1355 kfree(server->session_key.response);
1356 server->session_key.response = NULL;
1357 server->session_key.len = 0;
1358 kfree(server->hostname);
1360 task = xchg(&server->tsk, NULL);
1362 send_sig(SIGKILL, task, 1);
1365 struct TCP_Server_Info *
1366 cifs_get_tcp_session(struct smb3_fs_context *ctx)
1368 struct TCP_Server_Info *tcp_ses = NULL;
1371 cifs_dbg(FYI, "UNC: %s\n", ctx->UNC);
1373 /* see if we already have a matching tcp_ses */
1374 tcp_ses = cifs_find_tcp_session(ctx);
1378 tcp_ses = kzalloc(sizeof(struct TCP_Server_Info), GFP_KERNEL);
1384 tcp_ses->hostname = kstrdup(ctx->server_hostname, GFP_KERNEL);
1385 if (!tcp_ses->hostname) {
1390 tcp_ses->ops = ctx->ops;
1391 tcp_ses->vals = ctx->vals;
1392 cifs_set_net_ns(tcp_ses, get_net(current->nsproxy->net_ns));
1394 tcp_ses->conn_id = atomic_inc_return(&tcpSesNextId);
1395 tcp_ses->noblockcnt = ctx->rootfs;
1396 tcp_ses->noblocksnd = ctx->noblocksnd || ctx->rootfs;
1397 tcp_ses->noautotune = ctx->noautotune;
1398 tcp_ses->tcp_nodelay = ctx->sockopt_tcp_nodelay;
1399 tcp_ses->rdma = ctx->rdma;
1400 tcp_ses->in_flight = 0;
1401 tcp_ses->max_in_flight = 0;
1402 tcp_ses->credits = 1;
1403 init_waitqueue_head(&tcp_ses->response_q);
1404 init_waitqueue_head(&tcp_ses->request_q);
1405 INIT_LIST_HEAD(&tcp_ses->pending_mid_q);
1406 mutex_init(&tcp_ses->srv_mutex);
1407 memcpy(tcp_ses->workstation_RFC1001_name,
1408 ctx->source_rfc1001_name, RFC1001_NAME_LEN_WITH_NULL);
1409 memcpy(tcp_ses->server_RFC1001_name,
1410 ctx->target_rfc1001_name, RFC1001_NAME_LEN_WITH_NULL);
1411 tcp_ses->session_estab = false;
1412 tcp_ses->sequence_number = 0;
1413 tcp_ses->reconnect_instance = 1;
1414 tcp_ses->lstrp = jiffies;
1415 tcp_ses->compress_algorithm = cpu_to_le16(ctx->compression);
1416 spin_lock_init(&tcp_ses->req_lock);
1417 INIT_LIST_HEAD(&tcp_ses->tcp_ses_list);
1418 INIT_LIST_HEAD(&tcp_ses->smb_ses_list);
1419 INIT_DELAYED_WORK(&tcp_ses->echo, cifs_echo_request);
1420 INIT_DELAYED_WORK(&tcp_ses->resolve, cifs_resolve_server);
1421 INIT_DELAYED_WORK(&tcp_ses->reconnect, smb2_reconnect_server);
1422 mutex_init(&tcp_ses->reconnect_mutex);
1423 memcpy(&tcp_ses->srcaddr, &ctx->srcaddr,
1424 sizeof(tcp_ses->srcaddr));
1425 memcpy(&tcp_ses->dstaddr, &ctx->dstaddr,
1426 sizeof(tcp_ses->dstaddr));
1427 if (ctx->use_client_guid)
1428 memcpy(tcp_ses->client_guid, ctx->client_guid,
1429 SMB2_CLIENT_GUID_SIZE);
1431 generate_random_uuid(tcp_ses->client_guid);
1433 * at this point we are the only ones with the pointer
1434 * to the struct since the kernel thread not created yet
1435 * no need to spinlock this init of tcpStatus or srv_count
1437 tcp_ses->tcpStatus = CifsNew;
1438 ++tcp_ses->srv_count;
1440 if (ctx->echo_interval >= SMB_ECHO_INTERVAL_MIN &&
1441 ctx->echo_interval <= SMB_ECHO_INTERVAL_MAX)
1442 tcp_ses->echo_interval = ctx->echo_interval * HZ;
1444 tcp_ses->echo_interval = SMB_ECHO_INTERVAL_DEFAULT * HZ;
1445 if (tcp_ses->rdma) {
1446 #ifndef CONFIG_CIFS_SMB_DIRECT
1447 cifs_dbg(VFS, "CONFIG_CIFS_SMB_DIRECT is not enabled\n");
1449 goto out_err_crypto_release;
1451 tcp_ses->smbd_conn = smbd_get_connection(
1452 tcp_ses, (struct sockaddr *)&ctx->dstaddr);
1453 if (tcp_ses->smbd_conn) {
1454 cifs_dbg(VFS, "RDMA transport established\n");
1456 goto smbd_connected;
1459 goto out_err_crypto_release;
1462 rc = ip_connect(tcp_ses);
1464 cifs_dbg(VFS, "Error connecting to socket. Aborting operation.\n");
1465 goto out_err_crypto_release;
1469 * since we're in a cifs function already, we know that
1470 * this will succeed. No need for try_module_get().
1472 __module_get(THIS_MODULE);
1473 tcp_ses->tsk = kthread_run(cifs_demultiplex_thread,
1475 if (IS_ERR(tcp_ses->tsk)) {
1476 rc = PTR_ERR(tcp_ses->tsk);
1477 cifs_dbg(VFS, "error %d create cifsd thread\n", rc);
1478 module_put(THIS_MODULE);
1479 goto out_err_crypto_release;
1481 tcp_ses->min_offload = ctx->min_offload;
1483 * at this point we are the only ones with the pointer
1484 * to the struct since the kernel thread not created yet
1485 * no need to spinlock this update of tcpStatus
1487 tcp_ses->tcpStatus = CifsNeedNegotiate;
1489 if ((ctx->max_credits < 20) || (ctx->max_credits > 60000))
1490 tcp_ses->max_credits = SMB2_MAX_CREDITS_AVAILABLE;
1492 tcp_ses->max_credits = ctx->max_credits;
1494 tcp_ses->nr_targets = 1;
1495 tcp_ses->ignore_signature = ctx->ignore_signature;
1496 /* thread spawned, put it on the list */
1497 spin_lock(&cifs_tcp_ses_lock);
1498 list_add(&tcp_ses->tcp_ses_list, &cifs_tcp_ses_list);
1499 spin_unlock(&cifs_tcp_ses_lock);
1501 cifs_fscache_get_client_cookie(tcp_ses);
1503 /* queue echo request delayed work */
1504 queue_delayed_work(cifsiod_wq, &tcp_ses->echo, tcp_ses->echo_interval);
1506 /* queue dns resolution delayed work */
1507 cifs_dbg(FYI, "%s: next dns resolution scheduled for %d seconds in the future\n",
1508 __func__, SMB_DNS_RESOLVE_INTERVAL_DEFAULT);
1510 queue_delayed_work(cifsiod_wq, &tcp_ses->resolve, (SMB_DNS_RESOLVE_INTERVAL_DEFAULT * HZ));
1514 out_err_crypto_release:
1515 cifs_crypto_secmech_release(tcp_ses);
1517 put_net(cifs_net_ns(tcp_ses));
1521 kfree(tcp_ses->hostname);
1522 if (tcp_ses->ssocket)
1523 sock_release(tcp_ses->ssocket);
1529 static int match_session(struct cifs_ses *ses, struct smb3_fs_context *ctx)
1531 if (ctx->sectype != Unspecified &&
1532 ctx->sectype != ses->sectype)
1536 * If an existing session is limited to less channels than
1537 * requested, it should not be reused
1539 if (ses->chan_max < ctx->max_channels)
1542 switch (ses->sectype) {
1544 if (!uid_eq(ctx->cred_uid, ses->cred_uid))
1548 /* NULL username means anonymous session */
1549 if (ses->user_name == NULL) {
1555 /* anything else takes username/password */
1556 if (strncmp(ses->user_name,
1557 ctx->username ? ctx->username : "",
1558 CIFS_MAX_USERNAME_LEN))
1560 if ((ctx->username && strlen(ctx->username) != 0) &&
1561 ses->password != NULL &&
1562 strncmp(ses->password,
1563 ctx->password ? ctx->password : "",
1564 CIFS_MAX_PASSWORD_LEN))
1571 * cifs_setup_ipc - helper to setup the IPC tcon for the session
1572 * @ses: smb session to issue the request on
1573 * @ctx: the superblock configuration context to use for building the
1574 * new tree connection for the IPC (interprocess communication RPC)
1576 * A new IPC connection is made and stored in the session
1577 * tcon_ipc. The IPC tcon has the same lifetime as the session.
1580 cifs_setup_ipc(struct cifs_ses *ses, struct smb3_fs_context *ctx)
1583 struct cifs_tcon *tcon;
1584 char unc[SERVER_NAME_LENGTH + sizeof("//x/IPC$")] = {0};
1586 struct TCP_Server_Info *server = ses->server;
1589 * If the mount request that resulted in the creation of the
1590 * session requires encryption, force IPC to be encrypted too.
1593 if (server->capabilities & SMB2_GLOBAL_CAP_ENCRYPTION)
1596 cifs_server_dbg(VFS,
1597 "IPC: server doesn't support encryption\n");
1602 tcon = tconInfoAlloc();
1606 scnprintf(unc, sizeof(unc), "\\\\%s\\IPC$", server->hostname);
1612 rc = server->ops->tree_connect(xid, ses, unc, tcon, ctx->local_nls);
1616 cifs_server_dbg(VFS, "failed to connect to IPC (rc=%d)\n", rc);
1621 cifs_dbg(FYI, "IPC tcon rc = %d ipc tid = %d\n", rc, tcon->tid);
1623 ses->tcon_ipc = tcon;
1629 * cifs_free_ipc - helper to release the session IPC tcon
1630 * @ses: smb session to unmount the IPC from
1632 * Needs to be called everytime a session is destroyed.
1634 * On session close, the IPC is closed and the server must release all tcons of the session.
1635 * No need to send a tree disconnect here.
1637 * Besides, it will make the server to not close durable and resilient files on session close, as
1638 * specified in MS-SMB2 3.3.5.6 Receiving an SMB2 LOGOFF Request.
1641 cifs_free_ipc(struct cifs_ses *ses)
1643 struct cifs_tcon *tcon = ses->tcon_ipc;
1649 ses->tcon_ipc = NULL;
1653 static struct cifs_ses *
1654 cifs_find_smb_ses(struct TCP_Server_Info *server, struct smb3_fs_context *ctx)
1656 struct cifs_ses *ses;
1658 spin_lock(&cifs_tcp_ses_lock);
1659 list_for_each_entry(ses, &server->smb_ses_list, smb_ses_list) {
1660 if (ses->status == CifsExiting)
1662 if (!match_session(ses, ctx))
1665 spin_unlock(&cifs_tcp_ses_lock);
1668 spin_unlock(&cifs_tcp_ses_lock);
1672 void cifs_put_smb_ses(struct cifs_ses *ses)
1674 unsigned int rc, xid;
1675 struct TCP_Server_Info *server = ses->server;
1676 cifs_dbg(FYI, "%s: ses_count=%d\n", __func__, ses->ses_count);
1678 spin_lock(&cifs_tcp_ses_lock);
1679 if (ses->status == CifsExiting) {
1680 spin_unlock(&cifs_tcp_ses_lock);
1684 cifs_dbg(FYI, "%s: ses_count=%d\n", __func__, ses->ses_count);
1685 cifs_dbg(FYI, "%s: ses ipc: %s\n", __func__, ses->tcon_ipc ? ses->tcon_ipc->treeName : "NONE");
1687 if (--ses->ses_count > 0) {
1688 spin_unlock(&cifs_tcp_ses_lock);
1691 spin_unlock(&cifs_tcp_ses_lock);
1693 /* ses_count can never go negative */
1694 WARN_ON(ses->ses_count < 0);
1696 spin_lock(&GlobalMid_Lock);
1697 if (ses->status == CifsGood)
1698 ses->status = CifsExiting;
1699 spin_unlock(&GlobalMid_Lock);
1703 if (ses->status == CifsExiting && server->ops->logoff) {
1705 rc = server->ops->logoff(xid, ses);
1707 cifs_server_dbg(VFS, "%s: Session Logoff failure rc=%d\n",
1712 spin_lock(&cifs_tcp_ses_lock);
1713 list_del_init(&ses->smb_ses_list);
1714 spin_unlock(&cifs_tcp_ses_lock);
1716 /* close any extra channels */
1717 if (ses->chan_count > 1) {
1720 for (i = 1; i < ses->chan_count; i++)
1721 cifs_put_tcp_session(ses->chans[i].server, 0);
1725 cifs_put_tcp_session(server, 0);
1730 /* strlen("cifs:a:") + CIFS_MAX_DOMAINNAME_LEN + 1 */
1731 #define CIFSCREDS_DESC_SIZE (7 + CIFS_MAX_DOMAINNAME_LEN + 1)
1733 /* Populate username and pw fields from keyring if possible */
1735 cifs_set_cifscreds(struct smb3_fs_context *ctx, struct cifs_ses *ses)
1739 const char *delim, *payload;
1743 struct TCP_Server_Info *server = ses->server;
1744 struct sockaddr_in *sa;
1745 struct sockaddr_in6 *sa6;
1746 const struct user_key_payload *upayload;
1748 desc = kmalloc(CIFSCREDS_DESC_SIZE, GFP_KERNEL);
1752 /* try to find an address key first */
1753 switch (server->dstaddr.ss_family) {
1755 sa = (struct sockaddr_in *)&server->dstaddr;
1756 sprintf(desc, "cifs:a:%pI4", &sa->sin_addr.s_addr);
1759 sa6 = (struct sockaddr_in6 *)&server->dstaddr;
1760 sprintf(desc, "cifs:a:%pI6c", &sa6->sin6_addr.s6_addr);
1763 cifs_dbg(FYI, "Bad ss_family (%hu)\n",
1764 server->dstaddr.ss_family);
1769 cifs_dbg(FYI, "%s: desc=%s\n", __func__, desc);
1770 key = request_key(&key_type_logon, desc, "");
1772 if (!ses->domainName) {
1773 cifs_dbg(FYI, "domainName is NULL\n");
1778 /* didn't work, try to find a domain key */
1779 sprintf(desc, "cifs:d:%s", ses->domainName);
1780 cifs_dbg(FYI, "%s: desc=%s\n", __func__, desc);
1781 key = request_key(&key_type_logon, desc, "");
1789 down_read(&key->sem);
1790 upayload = user_key_payload_locked(key);
1791 if (IS_ERR_OR_NULL(upayload)) {
1792 rc = upayload ? PTR_ERR(upayload) : -EINVAL;
1796 /* find first : in payload */
1797 payload = upayload->data;
1798 delim = strnchr(payload, upayload->datalen, ':');
1799 cifs_dbg(FYI, "payload=%s\n", payload);
1801 cifs_dbg(FYI, "Unable to find ':' in payload (datalen=%d)\n",
1807 len = delim - payload;
1808 if (len > CIFS_MAX_USERNAME_LEN || len <= 0) {
1809 cifs_dbg(FYI, "Bad value from username search (len=%zd)\n",
1815 ctx->username = kstrndup(payload, len, GFP_KERNEL);
1816 if (!ctx->username) {
1817 cifs_dbg(FYI, "Unable to allocate %zd bytes for username\n",
1822 cifs_dbg(FYI, "%s: username=%s\n", __func__, ctx->username);
1824 len = key->datalen - (len + 1);
1825 if (len > CIFS_MAX_PASSWORD_LEN || len <= 0) {
1826 cifs_dbg(FYI, "Bad len for password search (len=%zd)\n", len);
1828 kfree(ctx->username);
1829 ctx->username = NULL;
1834 ctx->password = kstrndup(delim, len, GFP_KERNEL);
1835 if (!ctx->password) {
1836 cifs_dbg(FYI, "Unable to allocate %zd bytes for password\n",
1839 kfree(ctx->username);
1840 ctx->username = NULL;
1845 * If we have a domain key then we must set the domainName in the
1848 if (is_domain && ses->domainName) {
1849 ctx->domainname = kstrdup(ses->domainName, GFP_KERNEL);
1850 if (!ctx->domainname) {
1851 cifs_dbg(FYI, "Unable to allocate %zd bytes for domain\n",
1854 kfree(ctx->username);
1855 ctx->username = NULL;
1856 kfree_sensitive(ctx->password);
1857 ctx->password = NULL;
1867 cifs_dbg(FYI, "%s: returning %d\n", __func__, rc);
1870 #else /* ! CONFIG_KEYS */
1872 cifs_set_cifscreds(struct smb3_fs_context *ctx __attribute__((unused)),
1873 struct cifs_ses *ses __attribute__((unused)))
1877 #endif /* CONFIG_KEYS */
1880 * cifs_get_smb_ses - get a session matching @ctx data from @server
1881 * @server: server to setup the session to
1882 * @ctx: superblock configuration context to use to setup the session
1884 * This function assumes it is being called from cifs_mount() where we
1885 * already got a server reference (server refcount +1). See
1886 * cifs_get_tcon() for refcount explanations.
1889 cifs_get_smb_ses(struct TCP_Server_Info *server, struct smb3_fs_context *ctx)
1893 struct cifs_ses *ses;
1894 struct sockaddr_in *addr = (struct sockaddr_in *)&server->dstaddr;
1895 struct sockaddr_in6 *addr6 = (struct sockaddr_in6 *)&server->dstaddr;
1899 ses = cifs_find_smb_ses(server, ctx);
1901 cifs_dbg(FYI, "Existing smb sess found (status=%d)\n",
1904 mutex_lock(&ses->session_mutex);
1905 rc = cifs_negotiate_protocol(xid, ses);
1907 mutex_unlock(&ses->session_mutex);
1908 /* problem -- put our ses reference */
1909 cifs_put_smb_ses(ses);
1913 if (ses->need_reconnect) {
1914 cifs_dbg(FYI, "Session needs reconnect\n");
1915 rc = cifs_setup_session(xid, ses,
1918 mutex_unlock(&ses->session_mutex);
1919 /* problem -- put our reference */
1920 cifs_put_smb_ses(ses);
1925 mutex_unlock(&ses->session_mutex);
1927 /* existing SMB ses has a server reference already */
1928 cifs_put_tcp_session(server, 0);
1933 cifs_dbg(FYI, "Existing smb sess not found\n");
1934 ses = sesInfoAlloc();
1938 /* new SMB session uses our server ref */
1939 ses->server = server;
1940 if (server->dstaddr.ss_family == AF_INET6)
1941 sprintf(ses->ip_addr, "%pI6", &addr6->sin6_addr);
1943 sprintf(ses->ip_addr, "%pI4", &addr->sin_addr);
1945 if (ctx->username) {
1946 ses->user_name = kstrdup(ctx->username, GFP_KERNEL);
1947 if (!ses->user_name)
1951 /* ctx->password freed at unmount */
1952 if (ctx->password) {
1953 ses->password = kstrdup(ctx->password, GFP_KERNEL);
1957 if (ctx->domainname) {
1958 ses->domainName = kstrdup(ctx->domainname, GFP_KERNEL);
1959 if (!ses->domainName)
1962 if (ctx->workstation_name) {
1963 ses->workstation_name = kstrdup(ctx->workstation_name,
1965 if (!ses->workstation_name)
1968 if (ctx->domainauto)
1969 ses->domainAuto = ctx->domainauto;
1970 ses->cred_uid = ctx->cred_uid;
1971 ses->linux_uid = ctx->linux_uid;
1973 ses->sectype = ctx->sectype;
1974 ses->sign = ctx->sign;
1975 mutex_lock(&ses->session_mutex);
1977 /* add server as first channel */
1978 ses->chans[0].server = server;
1979 ses->chan_count = 1;
1980 ses->chan_max = ctx->multichannel ? ctx->max_channels:1;
1982 rc = cifs_negotiate_protocol(xid, ses);
1984 rc = cifs_setup_session(xid, ses, ctx->local_nls);
1986 /* each channel uses a different signing key */
1987 memcpy(ses->chans[0].signkey, ses->smb3signingkey,
1988 sizeof(ses->smb3signingkey));
1990 mutex_unlock(&ses->session_mutex);
1994 /* success, put it on the list and add it as first channel */
1995 spin_lock(&cifs_tcp_ses_lock);
1996 list_add(&ses->smb_ses_list, &server->smb_ses_list);
1997 spin_unlock(&cifs_tcp_ses_lock);
2001 cifs_setup_ipc(ses, ctx);
2011 static int match_tcon(struct cifs_tcon *tcon, struct smb3_fs_context *ctx)
2013 if (tcon->tidStatus == CifsExiting)
2015 if (strncmp(tcon->treeName, ctx->UNC, MAX_TREE_SIZE))
2017 if (tcon->seal != ctx->seal)
2019 if (tcon->snapshot_time != ctx->snapshot_time)
2021 if (tcon->handle_timeout != ctx->handle_timeout)
2023 if (tcon->no_lease != ctx->no_lease)
2025 if (tcon->nodelete != ctx->nodelete)
2030 static struct cifs_tcon *
2031 cifs_find_tcon(struct cifs_ses *ses, struct smb3_fs_context *ctx)
2033 struct list_head *tmp;
2034 struct cifs_tcon *tcon;
2036 spin_lock(&cifs_tcp_ses_lock);
2037 list_for_each(tmp, &ses->tcon_list) {
2038 tcon = list_entry(tmp, struct cifs_tcon, tcon_list);
2040 if (!match_tcon(tcon, ctx))
2043 spin_unlock(&cifs_tcp_ses_lock);
2046 spin_unlock(&cifs_tcp_ses_lock);
2051 cifs_put_tcon(struct cifs_tcon *tcon)
2054 struct cifs_ses *ses;
2057 * IPC tcon share the lifetime of their session and are
2058 * destroyed in the session put function
2060 if (tcon == NULL || tcon->ipc)
2064 cifs_dbg(FYI, "%s: tc_count=%d\n", __func__, tcon->tc_count);
2065 spin_lock(&cifs_tcp_ses_lock);
2066 if (--tcon->tc_count > 0) {
2067 spin_unlock(&cifs_tcp_ses_lock);
2071 /* tc_count can never go negative */
2072 WARN_ON(tcon->tc_count < 0);
2074 if (tcon->use_witness) {
2077 rc = cifs_swn_unregister(tcon);
2079 cifs_dbg(VFS, "%s: Failed to unregister for witness notifications: %d\n",
2084 list_del_init(&tcon->tcon_list);
2085 spin_unlock(&cifs_tcp_ses_lock);
2088 if (ses->server->ops->tree_disconnect)
2089 ses->server->ops->tree_disconnect(xid, tcon);
2092 cifs_fscache_release_super_cookie(tcon);
2094 cifs_put_smb_ses(ses);
2098 * cifs_get_tcon - get a tcon matching @ctx data from @ses
2099 * @ses: smb session to issue the request on
2100 * @ctx: the superblock configuration context to use for building the
2102 * - tcon refcount is the number of mount points using the tcon.
2103 * - ses refcount is the number of tcon using the session.
2105 * 1. This function assumes it is being called from cifs_mount() where
2106 * we already got a session reference (ses refcount +1).
2108 * 2. Since we're in the context of adding a mount point, the end
2109 * result should be either:
2111 * a) a new tcon already allocated with refcount=1 (1 mount point) and
2112 * its session refcount incremented (1 new tcon). This +1 was
2113 * already done in (1).
2115 * b) an existing tcon with refcount+1 (add a mount point to it) and
2116 * identical ses refcount (no new tcon). Because of (1) we need to
2117 * decrement the ses refcount.
2119 static struct cifs_tcon *
2120 cifs_get_tcon(struct cifs_ses *ses, struct smb3_fs_context *ctx)
2123 struct cifs_tcon *tcon;
2125 tcon = cifs_find_tcon(ses, ctx);
2128 * tcon has refcount already incremented but we need to
2129 * decrement extra ses reference gotten by caller (case b)
2131 cifs_dbg(FYI, "Found match on UNC path\n");
2132 cifs_put_smb_ses(ses);
2136 if (!ses->server->ops->tree_connect) {
2141 tcon = tconInfoAlloc();
2147 if (ctx->snapshot_time) {
2148 if (ses->server->vals->protocol_id == 0) {
2150 "Use SMB2 or later for snapshot mount option\n");
2154 tcon->snapshot_time = ctx->snapshot_time;
2157 if (ctx->handle_timeout) {
2158 if (ses->server->vals->protocol_id == 0) {
2160 "Use SMB2.1 or later for handle timeout option\n");
2164 tcon->handle_timeout = ctx->handle_timeout;
2168 if (ctx->password) {
2169 tcon->password = kstrdup(ctx->password, GFP_KERNEL);
2170 if (!tcon->password) {
2177 if (ses->server->vals->protocol_id == 0) {
2179 "SMB3 or later required for encryption\n");
2182 } else if (tcon->ses->server->capabilities &
2183 SMB2_GLOBAL_CAP_ENCRYPTION)
2186 cifs_dbg(VFS, "Encryption is not supported on share\n");
2192 if (ctx->linux_ext) {
2193 if (ses->server->posix_ext_supported) {
2194 tcon->posix_extensions = true;
2195 pr_warn_once("SMB3.11 POSIX Extensions are experimental\n");
2197 cifs_dbg(VFS, "Server does not support mounting with posix SMB3.11 extensions\n");
2204 * BB Do we need to wrap session_mutex around this TCon call and Unix
2205 * SetFS as we do on SessSetup and reconnect?
2208 rc = ses->server->ops->tree_connect(xid, ses, ctx->UNC, tcon,
2211 cifs_dbg(FYI, "Tcon rc = %d\n", rc);
2215 tcon->use_persistent = false;
2216 /* check if SMB2 or later, CIFS does not support persistent handles */
2217 if (ctx->persistent) {
2218 if (ses->server->vals->protocol_id == 0) {
2220 "SMB3 or later required for persistent handles\n");
2223 } else if (ses->server->capabilities &
2224 SMB2_GLOBAL_CAP_PERSISTENT_HANDLES)
2225 tcon->use_persistent = true;
2226 else /* persistent handles requested but not supported */ {
2228 "Persistent handles not supported on share\n");
2232 } else if ((tcon->capabilities & SMB2_SHARE_CAP_CONTINUOUS_AVAILABILITY)
2233 && (ses->server->capabilities & SMB2_GLOBAL_CAP_PERSISTENT_HANDLES)
2234 && (ctx->nopersistent == false)) {
2235 cifs_dbg(FYI, "enabling persistent handles\n");
2236 tcon->use_persistent = true;
2237 } else if (ctx->resilient) {
2238 if (ses->server->vals->protocol_id == 0) {
2240 "SMB2.1 or later required for resilient handles\n");
2244 tcon->use_resilient = true;
2247 tcon->use_witness = false;
2248 if (IS_ENABLED(CONFIG_CIFS_SWN_UPCALL) && ctx->witness) {
2249 if (ses->server->vals->protocol_id >= SMB30_PROT_ID) {
2250 if (tcon->capabilities & SMB2_SHARE_CAP_CLUSTER) {
2252 * Set witness in use flag in first place
2253 * to retry registration in the echo task
2255 tcon->use_witness = true;
2256 /* And try to register immediately */
2257 rc = cifs_swn_register(tcon);
2259 cifs_dbg(VFS, "Failed to register for witness notifications: %d\n", rc);
2263 /* TODO: try to extend for non-cluster uses (eg multichannel) */
2264 cifs_dbg(VFS, "witness requested on mount but no CLUSTER capability on share\n");
2269 cifs_dbg(VFS, "SMB3 or later required for witness option\n");
2275 /* If the user really knows what they are doing they can override */
2276 if (tcon->share_flags & SMB2_SHAREFLAG_NO_CACHING) {
2278 cifs_dbg(VFS, "cache=ro requested on mount but NO_CACHING flag set on share\n");
2279 else if (ctx->cache_rw)
2280 cifs_dbg(VFS, "cache=singleclient requested on mount but NO_CACHING flag set on share\n");
2283 if (ctx->no_lease) {
2284 if (ses->server->vals->protocol_id == 0) {
2286 "SMB2 or later required for nolease option\n");
2290 tcon->no_lease = ctx->no_lease;
2294 * We can have only one retry value for a connection to a share so for
2295 * resources mounted more than once to the same server share the last
2296 * value passed in for the retry flag is used.
2298 tcon->retry = ctx->retry;
2299 tcon->nocase = ctx->nocase;
2300 if (ses->server->capabilities & SMB2_GLOBAL_CAP_DIRECTORY_LEASING)
2301 tcon->nohandlecache = ctx->nohandlecache;
2303 tcon->nohandlecache = true;
2304 tcon->nodelete = ctx->nodelete;
2305 tcon->local_lease = ctx->local_lease;
2306 INIT_LIST_HEAD(&tcon->pending_opens);
2308 spin_lock(&cifs_tcp_ses_lock);
2309 list_add(&tcon->tcon_list, &ses->tcon_list);
2310 spin_unlock(&cifs_tcp_ses_lock);
2312 cifs_fscache_get_super_cookie(tcon);
2322 cifs_put_tlink(struct tcon_link *tlink)
2324 if (!tlink || IS_ERR(tlink))
2327 if (!atomic_dec_and_test(&tlink->tl_count) ||
2328 test_bit(TCON_LINK_IN_TREE, &tlink->tl_flags)) {
2329 tlink->tl_time = jiffies;
2333 if (!IS_ERR(tlink_tcon(tlink)))
2334 cifs_put_tcon(tlink_tcon(tlink));
2340 compare_mount_options(struct super_block *sb, struct cifs_mnt_data *mnt_data)
2342 struct cifs_sb_info *old = CIFS_SB(sb);
2343 struct cifs_sb_info *new = mnt_data->cifs_sb;
2344 unsigned int oldflags = old->mnt_cifs_flags & CIFS_MOUNT_MASK;
2345 unsigned int newflags = new->mnt_cifs_flags & CIFS_MOUNT_MASK;
2347 if ((sb->s_flags & CIFS_MS_MASK) != (mnt_data->flags & CIFS_MS_MASK))
2350 if (old->mnt_cifs_serverino_autodisabled)
2351 newflags &= ~CIFS_MOUNT_SERVER_INUM;
2353 if (oldflags != newflags)
2357 * We want to share sb only if we don't specify an r/wsize or
2358 * specified r/wsize is greater than or equal to existing one.
2360 if (new->ctx->wsize && new->ctx->wsize < old->ctx->wsize)
2363 if (new->ctx->rsize && new->ctx->rsize < old->ctx->rsize)
2366 if (!uid_eq(old->ctx->linux_uid, new->ctx->linux_uid) ||
2367 !gid_eq(old->ctx->linux_gid, new->ctx->linux_gid))
2370 if (old->ctx->file_mode != new->ctx->file_mode ||
2371 old->ctx->dir_mode != new->ctx->dir_mode)
2374 if (strcmp(old->local_nls->charset, new->local_nls->charset))
2377 if (old->ctx->acregmax != new->ctx->acregmax)
2379 if (old->ctx->acdirmax != new->ctx->acdirmax)
2386 match_prepath(struct super_block *sb, struct cifs_mnt_data *mnt_data)
2388 struct cifs_sb_info *old = CIFS_SB(sb);
2389 struct cifs_sb_info *new = mnt_data->cifs_sb;
2390 bool old_set = (old->mnt_cifs_flags & CIFS_MOUNT_USE_PREFIX_PATH) &&
2392 bool new_set = (new->mnt_cifs_flags & CIFS_MOUNT_USE_PREFIX_PATH) &&
2395 if (old_set && new_set && !strcmp(new->prepath, old->prepath))
2397 else if (!old_set && !new_set)
2404 cifs_match_super(struct super_block *sb, void *data)
2406 struct cifs_mnt_data *mnt_data = (struct cifs_mnt_data *)data;
2407 struct smb3_fs_context *ctx;
2408 struct cifs_sb_info *cifs_sb;
2409 struct TCP_Server_Info *tcp_srv;
2410 struct cifs_ses *ses;
2411 struct cifs_tcon *tcon;
2412 struct tcon_link *tlink;
2415 spin_lock(&cifs_tcp_ses_lock);
2416 cifs_sb = CIFS_SB(sb);
2417 tlink = cifs_get_tlink(cifs_sb_master_tlink(cifs_sb));
2418 if (tlink == NULL) {
2419 /* can not match superblock if tlink were ever null */
2420 spin_unlock(&cifs_tcp_ses_lock);
2423 tcon = tlink_tcon(tlink);
2425 tcp_srv = ses->server;
2427 ctx = mnt_data->ctx;
2429 if (!match_server(tcp_srv, ctx) ||
2430 !match_session(ses, ctx) ||
2431 !match_tcon(tcon, ctx) ||
2432 !match_prepath(sb, mnt_data)) {
2437 rc = compare_mount_options(sb, mnt_data);
2439 spin_unlock(&cifs_tcp_ses_lock);
2440 cifs_put_tlink(tlink);
2444 #ifdef CONFIG_DEBUG_LOCK_ALLOC
2445 static struct lock_class_key cifs_key[2];
2446 static struct lock_class_key cifs_slock_key[2];
2449 cifs_reclassify_socket4(struct socket *sock)
2451 struct sock *sk = sock->sk;
2452 BUG_ON(!sock_allow_reclassification(sk));
2453 sock_lock_init_class_and_name(sk, "slock-AF_INET-CIFS",
2454 &cifs_slock_key[0], "sk_lock-AF_INET-CIFS", &cifs_key[0]);
2458 cifs_reclassify_socket6(struct socket *sock)
2460 struct sock *sk = sock->sk;
2461 BUG_ON(!sock_allow_reclassification(sk));
2462 sock_lock_init_class_and_name(sk, "slock-AF_INET6-CIFS",
2463 &cifs_slock_key[1], "sk_lock-AF_INET6-CIFS", &cifs_key[1]);
2467 cifs_reclassify_socket4(struct socket *sock)
2472 cifs_reclassify_socket6(struct socket *sock)
2477 /* See RFC1001 section 14 on representation of Netbios names */
2478 static void rfc1002mangle(char *target, char *source, unsigned int length)
2482 for (i = 0, j = 0; i < (length); i++) {
2483 /* mask a nibble at a time and encode */
2484 target[j] = 'A' + (0x0F & (source[i] >> 4));
2485 target[j+1] = 'A' + (0x0F & source[i]);
2492 bind_socket(struct TCP_Server_Info *server)
2495 if (server->srcaddr.ss_family != AF_UNSPEC) {
2496 /* Bind to the specified local IP address */
2497 struct socket *socket = server->ssocket;
2498 rc = socket->ops->bind(socket,
2499 (struct sockaddr *) &server->srcaddr,
2500 sizeof(server->srcaddr));
2502 struct sockaddr_in *saddr4;
2503 struct sockaddr_in6 *saddr6;
2504 saddr4 = (struct sockaddr_in *)&server->srcaddr;
2505 saddr6 = (struct sockaddr_in6 *)&server->srcaddr;
2506 if (saddr6->sin6_family == AF_INET6)
2507 cifs_server_dbg(VFS, "Failed to bind to: %pI6c, error: %d\n",
2508 &saddr6->sin6_addr, rc);
2510 cifs_server_dbg(VFS, "Failed to bind to: %pI4, error: %d\n",
2511 &saddr4->sin_addr.s_addr, rc);
2518 ip_rfc1001_connect(struct TCP_Server_Info *server)
2522 * some servers require RFC1001 sessinit before sending
2523 * negprot - BB check reconnection in case where second
2524 * sessinit is sent but no second negprot
2526 struct rfc1002_session_packet *ses_init_buf;
2527 struct smb_hdr *smb_buf;
2528 ses_init_buf = kzalloc(sizeof(struct rfc1002_session_packet),
2531 ses_init_buf->trailer.session_req.called_len = 32;
2533 if (server->server_RFC1001_name[0] != 0)
2534 rfc1002mangle(ses_init_buf->trailer.
2535 session_req.called_name,
2536 server->server_RFC1001_name,
2537 RFC1001_NAME_LEN_WITH_NULL);
2539 rfc1002mangle(ses_init_buf->trailer.
2540 session_req.called_name,
2541 DEFAULT_CIFS_CALLED_NAME,
2542 RFC1001_NAME_LEN_WITH_NULL);
2544 ses_init_buf->trailer.session_req.calling_len = 32;
2547 * calling name ends in null (byte 16) from old smb
2550 if (server->workstation_RFC1001_name[0] != 0)
2551 rfc1002mangle(ses_init_buf->trailer.
2552 session_req.calling_name,
2553 server->workstation_RFC1001_name,
2554 RFC1001_NAME_LEN_WITH_NULL);
2556 rfc1002mangle(ses_init_buf->trailer.
2557 session_req.calling_name,
2559 RFC1001_NAME_LEN_WITH_NULL);
2561 ses_init_buf->trailer.session_req.scope1 = 0;
2562 ses_init_buf->trailer.session_req.scope2 = 0;
2563 smb_buf = (struct smb_hdr *)ses_init_buf;
2565 /* sizeof RFC1002_SESSION_REQUEST with no scope */
2566 smb_buf->smb_buf_length = cpu_to_be32(0x81000044);
2567 rc = smb_send(server, smb_buf, 0x44);
2568 kfree(ses_init_buf);
2570 * RFC1001 layer in at least one server
2571 * requires very short break before negprot
2572 * presumably because not expecting negprot
2573 * to follow so fast. This is a simple
2574 * solution that works without
2575 * complicating the code and causes no
2576 * significant slowing down on mount
2579 usleep_range(1000, 2000);
2582 * else the negprot may still work without this
2583 * even though malloc failed
2590 generic_ip_connect(struct TCP_Server_Info *server)
2595 struct socket *socket = server->ssocket;
2596 struct sockaddr *saddr;
2598 saddr = (struct sockaddr *) &server->dstaddr;
2600 if (server->dstaddr.ss_family == AF_INET6) {
2601 struct sockaddr_in6 *ipv6 = (struct sockaddr_in6 *)&server->dstaddr;
2603 sport = ipv6->sin6_port;
2604 slen = sizeof(struct sockaddr_in6);
2606 cifs_dbg(FYI, "%s: connecting to [%pI6]:%d\n", __func__, &ipv6->sin6_addr,
2609 struct sockaddr_in *ipv4 = (struct sockaddr_in *)&server->dstaddr;
2611 sport = ipv4->sin_port;
2612 slen = sizeof(struct sockaddr_in);
2614 cifs_dbg(FYI, "%s: connecting to %pI4:%d\n", __func__, &ipv4->sin_addr,
2618 if (socket == NULL) {
2619 rc = __sock_create(cifs_net_ns(server), sfamily, SOCK_STREAM,
2620 IPPROTO_TCP, &socket, 1);
2622 cifs_server_dbg(VFS, "Error %d creating socket\n", rc);
2623 server->ssocket = NULL;
2627 /* BB other socket options to set KEEPALIVE, NODELAY? */
2628 cifs_dbg(FYI, "Socket created\n");
2629 server->ssocket = socket;
2630 socket->sk->sk_allocation = GFP_NOFS;
2631 if (sfamily == AF_INET6)
2632 cifs_reclassify_socket6(socket);
2634 cifs_reclassify_socket4(socket);
2637 rc = bind_socket(server);
2642 * Eventually check for other socket options to change from
2643 * the default. sock_setsockopt not used because it expects
2646 socket->sk->sk_rcvtimeo = 7 * HZ;
2647 socket->sk->sk_sndtimeo = 5 * HZ;
2649 /* make the bufsizes depend on wsize/rsize and max requests */
2650 if (server->noautotune) {
2651 if (socket->sk->sk_sndbuf < (200 * 1024))
2652 socket->sk->sk_sndbuf = 200 * 1024;
2653 if (socket->sk->sk_rcvbuf < (140 * 1024))
2654 socket->sk->sk_rcvbuf = 140 * 1024;
2657 if (server->tcp_nodelay)
2658 tcp_sock_set_nodelay(socket->sk);
2660 cifs_dbg(FYI, "sndbuf %d rcvbuf %d rcvtimeo 0x%lx\n",
2661 socket->sk->sk_sndbuf,
2662 socket->sk->sk_rcvbuf, socket->sk->sk_rcvtimeo);
2664 rc = socket->ops->connect(socket, saddr, slen,
2665 server->noblockcnt ? O_NONBLOCK : 0);
2667 * When mounting SMB root file systems, we do not want to block in
2668 * connect. Otherwise bail out and then let cifs_reconnect() perform
2669 * reconnect failover - if possible.
2671 if (server->noblockcnt && rc == -EINPROGRESS)
2674 cifs_dbg(FYI, "Error %d connecting to server\n", rc);
2675 trace_smb3_connect_err(server->hostname, server->conn_id, &server->dstaddr, rc);
2676 sock_release(socket);
2677 server->ssocket = NULL;
2680 trace_smb3_connect_done(server->hostname, server->conn_id, &server->dstaddr);
2681 if (sport == htons(RFC1001_PORT))
2682 rc = ip_rfc1001_connect(server);
2688 ip_connect(struct TCP_Server_Info *server)
2691 struct sockaddr_in6 *addr6 = (struct sockaddr_in6 *)&server->dstaddr;
2692 struct sockaddr_in *addr = (struct sockaddr_in *)&server->dstaddr;
2694 if (server->dstaddr.ss_family == AF_INET6)
2695 sport = &addr6->sin6_port;
2697 sport = &addr->sin_port;
2702 /* try with 445 port at first */
2703 *sport = htons(CIFS_PORT);
2705 rc = generic_ip_connect(server);
2709 /* if it failed, try with 139 port */
2710 *sport = htons(RFC1001_PORT);
2713 return generic_ip_connect(server);
2716 void reset_cifs_unix_caps(unsigned int xid, struct cifs_tcon *tcon,
2717 struct cifs_sb_info *cifs_sb, struct smb3_fs_context *ctx)
2720 * If we are reconnecting then should we check to see if
2721 * any requested capabilities changed locally e.g. via
2722 * remount but we can not do much about it here
2723 * if they have (even if we could detect it by the following)
2724 * Perhaps we could add a backpointer to array of sb from tcon
2725 * or if we change to make all sb to same share the same
2726 * sb as NFS - then we only have one backpointer to sb.
2727 * What if we wanted to mount the server share twice once with
2728 * and once without posixacls or posix paths?
2730 __u64 saved_cap = le64_to_cpu(tcon->fsUnixInfo.Capability);
2732 if (ctx && ctx->no_linux_ext) {
2733 tcon->fsUnixInfo.Capability = 0;
2734 tcon->unix_ext = 0; /* Unix Extensions disabled */
2735 cifs_dbg(FYI, "Linux protocol extensions disabled\n");
2738 tcon->unix_ext = 1; /* Unix Extensions supported */
2740 if (!tcon->unix_ext) {
2741 cifs_dbg(FYI, "Unix extensions disabled so not set on reconnect\n");
2745 if (!CIFSSMBQFSUnixInfo(xid, tcon)) {
2746 __u64 cap = le64_to_cpu(tcon->fsUnixInfo.Capability);
2747 cifs_dbg(FYI, "unix caps which server supports %lld\n", cap);
2749 * check for reconnect case in which we do not
2750 * want to change the mount behavior if we can avoid it
2754 * turn off POSIX ACL and PATHNAMES if not set
2755 * originally at mount time
2757 if ((saved_cap & CIFS_UNIX_POSIX_ACL_CAP) == 0)
2758 cap &= ~CIFS_UNIX_POSIX_ACL_CAP;
2759 if ((saved_cap & CIFS_UNIX_POSIX_PATHNAMES_CAP) == 0) {
2760 if (cap & CIFS_UNIX_POSIX_PATHNAMES_CAP)
2761 cifs_dbg(VFS, "POSIXPATH support change\n");
2762 cap &= ~CIFS_UNIX_POSIX_PATHNAMES_CAP;
2763 } else if ((cap & CIFS_UNIX_POSIX_PATHNAMES_CAP) == 0) {
2764 cifs_dbg(VFS, "possible reconnect error\n");
2765 cifs_dbg(VFS, "server disabled POSIX path support\n");
2769 if (cap & CIFS_UNIX_TRANSPORT_ENCRYPTION_MANDATORY_CAP)
2770 cifs_dbg(VFS, "per-share encryption not supported yet\n");
2772 cap &= CIFS_UNIX_CAP_MASK;
2773 if (ctx && ctx->no_psx_acl)
2774 cap &= ~CIFS_UNIX_POSIX_ACL_CAP;
2775 else if (CIFS_UNIX_POSIX_ACL_CAP & cap) {
2776 cifs_dbg(FYI, "negotiated posix acl support\n");
2778 cifs_sb->mnt_cifs_flags |=
2779 CIFS_MOUNT_POSIXACL;
2782 if (ctx && ctx->posix_paths == 0)
2783 cap &= ~CIFS_UNIX_POSIX_PATHNAMES_CAP;
2784 else if (cap & CIFS_UNIX_POSIX_PATHNAMES_CAP) {
2785 cifs_dbg(FYI, "negotiate posix pathnames\n");
2787 cifs_sb->mnt_cifs_flags |=
2788 CIFS_MOUNT_POSIX_PATHS;
2791 cifs_dbg(FYI, "Negotiate caps 0x%x\n", (int)cap);
2792 #ifdef CONFIG_CIFS_DEBUG2
2793 if (cap & CIFS_UNIX_FCNTL_CAP)
2794 cifs_dbg(FYI, "FCNTL cap\n");
2795 if (cap & CIFS_UNIX_EXTATTR_CAP)
2796 cifs_dbg(FYI, "EXTATTR cap\n");
2797 if (cap & CIFS_UNIX_POSIX_PATHNAMES_CAP)
2798 cifs_dbg(FYI, "POSIX path cap\n");
2799 if (cap & CIFS_UNIX_XATTR_CAP)
2800 cifs_dbg(FYI, "XATTR cap\n");
2801 if (cap & CIFS_UNIX_POSIX_ACL_CAP)
2802 cifs_dbg(FYI, "POSIX ACL cap\n");
2803 if (cap & CIFS_UNIX_LARGE_READ_CAP)
2804 cifs_dbg(FYI, "very large read cap\n");
2805 if (cap & CIFS_UNIX_LARGE_WRITE_CAP)
2806 cifs_dbg(FYI, "very large write cap\n");
2807 if (cap & CIFS_UNIX_TRANSPORT_ENCRYPTION_CAP)
2808 cifs_dbg(FYI, "transport encryption cap\n");
2809 if (cap & CIFS_UNIX_TRANSPORT_ENCRYPTION_MANDATORY_CAP)
2810 cifs_dbg(FYI, "mandatory transport encryption cap\n");
2811 #endif /* CIFS_DEBUG2 */
2812 if (CIFSSMBSetFSUnixInfo(xid, tcon, cap)) {
2814 cifs_dbg(FYI, "resetting capabilities failed\n");
2816 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");
2822 int cifs_setup_cifs_sb(struct cifs_sb_info *cifs_sb)
2824 struct smb3_fs_context *ctx = cifs_sb->ctx;
2826 INIT_DELAYED_WORK(&cifs_sb->prune_tlinks, cifs_prune_tlinks);
2828 spin_lock_init(&cifs_sb->tlink_tree_lock);
2829 cifs_sb->tlink_tree = RB_ROOT;
2831 cifs_dbg(FYI, "file mode: %04ho dir mode: %04ho\n",
2832 ctx->file_mode, ctx->dir_mode);
2834 /* this is needed for ASCII cp to Unicode converts */
2835 if (ctx->iocharset == NULL) {
2836 /* load_nls_default cannot return null */
2837 cifs_sb->local_nls = load_nls_default();
2839 cifs_sb->local_nls = load_nls(ctx->iocharset);
2840 if (cifs_sb->local_nls == NULL) {
2841 cifs_dbg(VFS, "CIFS mount error: iocharset %s not found\n",
2846 ctx->local_nls = cifs_sb->local_nls;
2848 smb3_update_mnt_flags(cifs_sb);
2851 cifs_dbg(FYI, "mounting share using direct i/o\n");
2852 if (ctx->cache_ro) {
2853 cifs_dbg(VFS, "mounting share with read only caching. Ensure that the share will not be modified while in use.\n");
2854 cifs_sb->mnt_cifs_flags |= CIFS_MOUNT_RO_CACHE;
2855 } else if (ctx->cache_rw) {
2856 cifs_dbg(VFS, "mounting share in single client RW caching mode. Ensure that no other systems will be accessing the share.\n");
2857 cifs_sb->mnt_cifs_flags |= (CIFS_MOUNT_RO_CACHE |
2858 CIFS_MOUNT_RW_CACHE);
2861 if ((ctx->cifs_acl) && (ctx->dynperm))
2862 cifs_dbg(VFS, "mount option dynperm ignored if cifsacl mount option supported\n");
2865 cifs_sb->prepath = kstrdup(ctx->prepath, GFP_KERNEL);
2866 if (cifs_sb->prepath == NULL)
2868 cifs_sb->mnt_cifs_flags |= CIFS_MOUNT_USE_PREFIX_PATH;
2874 /* Release all succeed connections */
2875 static inline void mount_put_conns(struct cifs_sb_info *cifs_sb,
2877 struct TCP_Server_Info *server,
2878 struct cifs_ses *ses, struct cifs_tcon *tcon)
2883 cifs_put_tcon(tcon);
2885 cifs_put_smb_ses(ses);
2887 cifs_put_tcp_session(server, 0);
2888 cifs_sb->mnt_cifs_flags &= ~CIFS_MOUNT_POSIX_PATHS;
2892 /* Get connections for tcp, ses and tcon */
2893 static int mount_get_conns(struct smb3_fs_context *ctx, struct cifs_sb_info *cifs_sb,
2895 struct TCP_Server_Info **nserver,
2896 struct cifs_ses **nses, struct cifs_tcon **ntcon)
2899 struct TCP_Server_Info *server;
2900 struct cifs_ses *ses;
2901 struct cifs_tcon *tcon;
2909 /* get a reference to a tcp session */
2910 server = cifs_get_tcp_session(ctx);
2911 if (IS_ERR(server)) {
2912 rc = PTR_ERR(server);
2918 /* get a reference to a SMB session */
2919 ses = cifs_get_smb_ses(server, ctx);
2927 if ((ctx->persistent == true) && (!(ses->server->capabilities &
2928 SMB2_GLOBAL_CAP_PERSISTENT_HANDLES))) {
2929 cifs_server_dbg(VFS, "persistent handles not supported by server\n");
2933 /* search for existing tcon to this server share */
2934 tcon = cifs_get_tcon(ses, ctx);
2942 /* if new SMB3.11 POSIX extensions are supported do not remap / and \ */
2943 if (tcon->posix_extensions)
2944 cifs_sb->mnt_cifs_flags |= CIFS_MOUNT_POSIX_PATHS;
2946 /* tell server which Unix caps we support */
2947 if (cap_unix(tcon->ses)) {
2949 * reset of caps checks mount to see if unix extensions disabled
2950 * for just this mount.
2952 reset_cifs_unix_caps(*xid, tcon, cifs_sb, ctx);
2953 if ((tcon->ses->server->tcpStatus == CifsNeedReconnect) &&
2954 (le64_to_cpu(tcon->fsUnixInfo.Capability) &
2955 CIFS_UNIX_TRANSPORT_ENCRYPTION_MANDATORY_CAP))
2958 tcon->unix_ext = 0; /* server does not support them */
2960 /* do not care if a following call succeed - informational */
2961 if (!tcon->pipe && server->ops->qfs_tcon) {
2962 server->ops->qfs_tcon(*xid, tcon, cifs_sb);
2963 if (cifs_sb->mnt_cifs_flags & CIFS_MOUNT_RO_CACHE) {
2964 if (tcon->fsDevInfo.DeviceCharacteristics &
2965 cpu_to_le32(FILE_READ_ONLY_DEVICE))
2966 cifs_dbg(VFS, "mounted to read only share\n");
2967 else if ((cifs_sb->mnt_cifs_flags &
2968 CIFS_MOUNT_RW_CACHE) == 0)
2969 cifs_dbg(VFS, "read only mount of RW share\n");
2970 /* no need to log a RW mount of a typical RW share */
2975 * Clamp the rsize/wsize mount arguments if they are too big for the server
2976 * and set the rsize/wsize to the negotiated values if not passed in by
2979 if ((cifs_sb->ctx->wsize == 0) ||
2980 (cifs_sb->ctx->wsize > server->ops->negotiate_wsize(tcon, ctx)))
2981 cifs_sb->ctx->wsize = server->ops->negotiate_wsize(tcon, ctx);
2982 if ((cifs_sb->ctx->rsize == 0) ||
2983 (cifs_sb->ctx->rsize > server->ops->negotiate_rsize(tcon, ctx)))
2984 cifs_sb->ctx->rsize = server->ops->negotiate_rsize(tcon, ctx);
2989 static int mount_setup_tlink(struct cifs_sb_info *cifs_sb, struct cifs_ses *ses,
2990 struct cifs_tcon *tcon)
2992 struct tcon_link *tlink;
2994 /* hang the tcon off of the superblock */
2995 tlink = kzalloc(sizeof(*tlink), GFP_KERNEL);
2999 tlink->tl_uid = ses->linux_uid;
3000 tlink->tl_tcon = tcon;
3001 tlink->tl_time = jiffies;
3002 set_bit(TCON_LINK_MASTER, &tlink->tl_flags);
3003 set_bit(TCON_LINK_IN_TREE, &tlink->tl_flags);
3005 cifs_sb->master_tlink = tlink;
3006 spin_lock(&cifs_sb->tlink_tree_lock);
3007 tlink_rb_insert(&cifs_sb->tlink_tree, tlink);
3008 spin_unlock(&cifs_sb->tlink_tree_lock);
3010 queue_delayed_work(cifsiod_wq, &cifs_sb->prune_tlinks,
3015 #ifdef CONFIG_CIFS_DFS_UPCALL
3016 static int mount_get_dfs_conns(struct smb3_fs_context *ctx, struct cifs_sb_info *cifs_sb,
3017 unsigned int *xid, struct TCP_Server_Info **nserver,
3018 struct cifs_ses **nses, struct cifs_tcon **ntcon)
3022 ctx->nosharesock = true;
3023 rc = mount_get_conns(ctx, cifs_sb, xid, nserver, nses, ntcon);
3025 cifs_dbg(FYI, "%s: marking tcp session as a dfs connection\n", __func__);
3026 spin_lock(&cifs_tcp_ses_lock);
3027 (*nserver)->is_dfs_conn = true;
3028 spin_unlock(&cifs_tcp_ses_lock);
3034 * cifs_build_path_to_root returns full path to root when we do not have an
3035 * existing connection (tcon)
3038 build_unc_path_to_root(const struct smb3_fs_context *ctx,
3039 const struct cifs_sb_info *cifs_sb, bool useppath)
3041 char *full_path, *pos;
3042 unsigned int pplen = useppath && ctx->prepath ?
3043 strlen(ctx->prepath) + 1 : 0;
3044 unsigned int unc_len = strnlen(ctx->UNC, MAX_TREE_SIZE + 1);
3046 if (unc_len > MAX_TREE_SIZE)
3047 return ERR_PTR(-EINVAL);
3049 full_path = kmalloc(unc_len + pplen + 1, GFP_KERNEL);
3050 if (full_path == NULL)
3051 return ERR_PTR(-ENOMEM);
3053 memcpy(full_path, ctx->UNC, unc_len);
3054 pos = full_path + unc_len;
3057 *pos = CIFS_DIR_SEP(cifs_sb);
3058 memcpy(pos + 1, ctx->prepath, pplen);
3062 *pos = '\0'; /* add trailing null */
3063 convert_delimiter(full_path, CIFS_DIR_SEP(cifs_sb));
3064 cifs_dbg(FYI, "%s: full_path=%s\n", __func__, full_path);
3069 * expand_dfs_referral - Perform a dfs referral query and update the cifs_sb
3071 * If a referral is found, cifs_sb->ctx->mount_options will be (re-)allocated
3072 * to a string containing updated options for the submount. Otherwise it
3073 * will be left untouched.
3075 * Returns the rc from get_dfs_path to the caller, which can be used to
3076 * determine whether there were referrals.
3079 expand_dfs_referral(const unsigned int xid, struct cifs_ses *ses,
3080 struct smb3_fs_context *ctx, struct cifs_sb_info *cifs_sb,
3084 struct dfs_info3_param referral = {0};
3085 char *full_path = NULL, *mdata = NULL;
3087 if (cifs_sb->mnt_cifs_flags & CIFS_MOUNT_NO_DFS)
3090 full_path = build_unc_path_to_root(ctx, cifs_sb, true);
3091 if (IS_ERR(full_path))
3092 return PTR_ERR(full_path);
3094 rc = dfs_cache_find(xid, ses, cifs_sb->local_nls, cifs_remap(cifs_sb),
3095 ref_path, &referral, NULL);
3097 char *fake_devname = NULL;
3099 mdata = cifs_compose_mount_options(cifs_sb->ctx->mount_options,
3100 full_path + 1, &referral,
3102 free_dfs_info_param(&referral);
3104 if (IS_ERR(mdata)) {
3105 rc = PTR_ERR(mdata);
3109 * We can not clear out the whole structure since we
3110 * no longer have an explicit function to parse
3111 * a mount-string. Instead we need to clear out the
3112 * individual fields that are no longer valid.
3114 kfree(ctx->prepath);
3115 ctx->prepath = NULL;
3116 rc = cifs_setup_volume_info(ctx, mdata, fake_devname);
3118 kfree(fake_devname);
3119 kfree(cifs_sb->ctx->mount_options);
3120 cifs_sb->ctx->mount_options = mdata;
3126 static int get_next_dfs_tgt(struct dfs_cache_tgt_list *tgt_list,
3127 struct dfs_cache_tgt_iterator **tgt_it)
3130 *tgt_it = dfs_cache_get_tgt_iterator(tgt_list);
3132 *tgt_it = dfs_cache_get_next_tgt(tgt_list, *tgt_it);
3133 return !*tgt_it ? -EHOSTDOWN : 0;
3136 static int update_vol_info(const struct dfs_cache_tgt_iterator *tgt_it,
3137 struct smb3_fs_context *fake_ctx, struct smb3_fs_context *ctx)
3139 const char *tgt = dfs_cache_get_tgt_name(tgt_it);
3140 int len = strlen(tgt) + 2;
3143 new_unc = kmalloc(len, GFP_KERNEL);
3146 scnprintf(new_unc, len, "\\%s", tgt);
3151 if (fake_ctx->prepath) {
3152 kfree(ctx->prepath);
3153 ctx->prepath = fake_ctx->prepath;
3154 fake_ctx->prepath = NULL;
3156 memcpy(&ctx->dstaddr, &fake_ctx->dstaddr, sizeof(ctx->dstaddr));
3161 static int do_dfs_failover(const char *path, const char *full_path, struct cifs_sb_info *cifs_sb,
3162 struct smb3_fs_context *ctx, struct cifs_ses *root_ses,
3163 unsigned int *xid, struct TCP_Server_Info **server,
3164 struct cifs_ses **ses, struct cifs_tcon **tcon)
3168 struct dfs_cache_tgt_list tgt_list = DFS_CACHE_TGT_LIST_INIT(tgt_list);
3169 struct dfs_cache_tgt_iterator *tgt_it = NULL;
3170 struct smb3_fs_context tmp_ctx = {NULL};
3172 if (cifs_sb->mnt_cifs_flags & CIFS_MOUNT_NO_DFS)
3175 npath = dfs_cache_canonical_path(path, cifs_sb->local_nls, cifs_remap(cifs_sb));
3177 return PTR_ERR(npath);
3179 cifs_dbg(FYI, "%s: path=%s full_path=%s\n", __func__, npath, full_path);
3181 rc = dfs_cache_noreq_find(npath, NULL, &tgt_list);
3185 * We use a 'tmp_ctx' here because we need pass it down to the mount_{get,put} functions to
3186 * test connection against new DFS targets.
3188 rc = smb3_fs_context_dup(&tmp_ctx, ctx);
3193 struct dfs_info3_param ref = {0};
3194 char *fake_devname = NULL, *mdata = NULL;
3196 /* Get next DFS target server - if any */
3197 rc = get_next_dfs_tgt(&tgt_list, &tgt_it);
3201 rc = dfs_cache_get_tgt_referral(npath, tgt_it, &ref);
3205 cifs_dbg(FYI, "%s: old ctx: UNC=%s prepath=%s\n", __func__, tmp_ctx.UNC,
3208 mdata = cifs_compose_mount_options(cifs_sb->ctx->mount_options, full_path + 1, &ref,
3210 free_dfs_info_param(&ref);
3212 if (IS_ERR(mdata)) {
3213 rc = PTR_ERR(mdata);
3216 rc = cifs_setup_volume_info(&tmp_ctx, mdata, fake_devname);
3219 kfree(fake_devname);
3224 cifs_dbg(FYI, "%s: new ctx: UNC=%s prepath=%s\n", __func__, tmp_ctx.UNC,
3227 mount_put_conns(cifs_sb, *xid, *server, *ses, *tcon);
3228 rc = mount_get_dfs_conns(&tmp_ctx, cifs_sb, xid, server, ses, tcon);
3229 if (!rc || (*server && *ses)) {
3231 * We were able to connect to new target server. Update current context with
3232 * new target server.
3234 rc = update_vol_info(tgt_it, &tmp_ctx, ctx);
3239 cifs_dbg(FYI, "%s: final ctx: UNC=%s prepath=%s\n", __func__, tmp_ctx.UNC,
3242 * Update DFS target hint in DFS referral cache with the target server we
3243 * successfully reconnected to.
3245 rc = dfs_cache_update_tgthint(*xid, root_ses ? root_ses : *ses, cifs_sb->local_nls,
3246 cifs_remap(cifs_sb), path, tgt_it);
3251 smb3_cleanup_fs_context_contents(&tmp_ctx);
3252 dfs_cache_free_tgts(&tgt_list);
3257 /* TODO: all callers to this are broken. We are not parsing mount_options here
3258 * we should pass a clone of the original context?
3261 cifs_setup_volume_info(struct smb3_fs_context *ctx, const char *mntopts, const char *devname)
3266 cifs_dbg(FYI, "%s: devname=%s\n", __func__, devname);
3267 rc = smb3_parse_devname(devname, ctx);
3269 cifs_dbg(VFS, "%s: failed to parse %s: %d\n", __func__, devname, rc);
3277 rc = smb3_parse_opt(mntopts, "ip", &ip);
3279 cifs_dbg(VFS, "%s: failed to parse ip options: %d\n", __func__, rc);
3283 rc = cifs_convert_address((struct sockaddr *)&ctx->dstaddr, ip, strlen(ip));
3286 cifs_dbg(VFS, "%s: failed to convert ip address\n", __func__);
3291 if (ctx->nullauth) {
3292 cifs_dbg(FYI, "Anonymous login\n");
3293 kfree(ctx->username);
3294 ctx->username = NULL;
3295 } else if (ctx->username) {
3296 /* BB fixme parse for domain name here */
3297 cifs_dbg(FYI, "Username: %s\n", ctx->username);
3299 cifs_dbg(VFS, "No username specified\n");
3300 /* In userspace mount helper we can get user name from alternate
3301 locations such as env variables and files on disk */
3309 cifs_are_all_path_components_accessible(struct TCP_Server_Info *server,
3311 struct cifs_tcon *tcon,
3312 struct cifs_sb_info *cifs_sb,
3319 int skip = added_treename ? 1 : 0;
3321 sep = CIFS_DIR_SEP(cifs_sb);
3324 rc = server->ops->is_path_accessible(xid, tcon, cifs_sb, "");
3326 /* skip separators */
3331 /* next separator */
3332 while (*s && *s != sep)
3335 * if the treename is added, we then have to skip the first
3336 * part within the separators
3343 * temporarily null-terminate the path at the end of
3344 * the current component
3348 rc = server->ops->is_path_accessible(xid, tcon, cifs_sb,
3356 * Check if path is remote (e.g. a DFS share). Return -EREMOTE if it is,
3359 static int is_path_remote(struct cifs_sb_info *cifs_sb, struct smb3_fs_context *ctx,
3360 const unsigned int xid,
3361 struct TCP_Server_Info *server,
3362 struct cifs_tcon *tcon)
3367 if (!server->ops->is_path_accessible)
3371 * cifs_build_path_to_root works only when we have a valid tcon
3373 full_path = cifs_build_path_to_root(ctx, cifs_sb, tcon,
3374 tcon->Flags & SMB_SHARE_IS_IN_DFS);
3375 if (full_path == NULL)
3378 cifs_dbg(FYI, "%s: full_path: %s\n", __func__, full_path);
3380 rc = server->ops->is_path_accessible(xid, tcon, cifs_sb,
3382 if (rc != 0 && rc != -EREMOTE) {
3387 if (rc != -EREMOTE) {
3388 rc = cifs_are_all_path_components_accessible(server, xid, tcon,
3389 cifs_sb, full_path, tcon->Flags & SMB_SHARE_IS_IN_DFS);
3391 cifs_server_dbg(VFS, "cannot query dirs between root and final path, enabling CIFS_MOUNT_USE_PREFIX_PATH\n");
3392 cifs_sb->mnt_cifs_flags |= CIFS_MOUNT_USE_PREFIX_PATH;
3401 #ifdef CONFIG_CIFS_DFS_UPCALL
3402 static void set_root_ses(struct cifs_sb_info *cifs_sb, const uuid_t *mount_id, struct cifs_ses *ses,
3403 struct cifs_ses **root_ses)
3406 spin_lock(&cifs_tcp_ses_lock);
3408 spin_unlock(&cifs_tcp_ses_lock);
3409 dfs_cache_add_refsrv_session(mount_id, ses);
3414 /* Set up next dfs prefix path in @dfs_path */
3415 static int next_dfs_prepath(struct cifs_sb_info *cifs_sb, struct smb3_fs_context *ctx,
3416 const unsigned int xid, struct TCP_Server_Info *server,
3417 struct cifs_tcon *tcon, char **dfs_path)
3420 int added_treename = is_tcon_dfs(tcon);
3423 path = cifs_build_path_to_root(ctx, cifs_sb, tcon, added_treename);
3427 rc = is_path_remote(cifs_sb, ctx, xid, server, tcon);
3428 if (rc == -EREMOTE) {
3429 struct smb3_fs_context v = {NULL};
3430 /* if @path contains a tree name, skip it in the prefix path */
3431 if (added_treename) {
3432 rc = smb3_parse_devname(path, &v);
3435 npath = build_unc_path_to_root(&v, cifs_sb, true);
3436 smb3_cleanup_fs_context_contents(&v);
3439 v.prepath = path + 1;
3440 npath = build_unc_path_to_root(&v, cifs_sb, true);
3443 if (IS_ERR(npath)) {
3444 rc = PTR_ERR(npath);
3458 /* Check if resolved targets can handle any DFS referrals */
3459 static int is_referral_server(const char *ref_path, struct cifs_sb_info *cifs_sb,
3460 struct cifs_tcon *tcon, bool *ref_server)
3463 struct dfs_info3_param ref = {0};
3465 cifs_dbg(FYI, "%s: ref_path=%s\n", __func__, ref_path);
3467 if (is_tcon_dfs(tcon)) {
3472 npath = dfs_cache_canonical_path(ref_path, cifs_sb->local_nls, cifs_remap(cifs_sb));
3474 return PTR_ERR(npath);
3476 rc = dfs_cache_noreq_find(npath, &ref, NULL);
3479 cifs_dbg(VFS, "%s: dfs_cache_noreq_find: failed (rc=%d)\n", __func__, rc);
3482 cifs_dbg(FYI, "%s: ref.flags=0x%x\n", __func__, ref.flags);
3484 * Check if all targets are capable of handling DFS referrals as per
3485 * MS-DFSC 2.2.4 RESP_GET_DFS_REFERRAL.
3487 *ref_server = !!(ref.flags & DFSREF_REFERRAL_SERVER);
3488 free_dfs_info_param(&ref);
3493 int cifs_mount(struct cifs_sb_info *cifs_sb, struct smb3_fs_context *ctx)
3497 struct TCP_Server_Info *server = NULL;
3498 struct cifs_ses *ses = NULL, *root_ses = NULL;
3499 struct cifs_tcon *tcon = NULL;
3501 uuid_t mount_id = {0};
3502 char *ref_path = NULL, *full_path = NULL;
3503 char *oldmnt = NULL;
3504 bool ref_server = false;
3506 rc = mount_get_conns(ctx, cifs_sb, &xid, &server, &ses, &tcon);
3508 * If called with 'nodfs' mount option, then skip DFS resolving. Otherwise unconditionally
3509 * try to get an DFS referral (even cached) to determine whether it is an DFS mount.
3511 * Skip prefix path to provide support for DFS referrals from w2k8 servers which don't seem
3512 * to respond with PATH_NOT_COVERED to requests that include the prefix.
3514 if ((cifs_sb->mnt_cifs_flags & CIFS_MOUNT_NO_DFS) ||
3515 dfs_cache_find(xid, ses, cifs_sb->local_nls, cifs_remap(cifs_sb), ctx->UNC + 1, NULL,
3519 /* Check if it is fully accessible and then mount it */
3520 rc = is_path_remote(cifs_sb, ctx, xid, server, tcon);
3527 mount_put_conns(cifs_sb, xid, server, ses, tcon);
3529 * Ignore error check here because we may failover to other targets from cached a
3532 (void)mount_get_dfs_conns(ctx, cifs_sb, &xid, &server, &ses, &tcon);
3534 /* Get path of DFS root */
3535 ref_path = build_unc_path_to_root(ctx, cifs_sb, false);
3536 if (IS_ERR(ref_path)) {
3537 rc = PTR_ERR(ref_path);
3542 uuid_gen(&mount_id);
3543 set_root_ses(cifs_sb, &mount_id, ses, &root_ses);
3545 /* Save full path of last DFS path we used to resolve final target server */
3547 full_path = build_unc_path_to_root(ctx, cifs_sb, !!count);
3548 if (IS_ERR(full_path)) {
3549 rc = PTR_ERR(full_path);
3553 /* Chase referral */
3554 oldmnt = cifs_sb->ctx->mount_options;
3555 rc = expand_dfs_referral(xid, root_ses, ctx, cifs_sb, ref_path + 1);
3558 /* Connect to new DFS target only if we were redirected */
3559 if (oldmnt != cifs_sb->ctx->mount_options) {
3560 mount_put_conns(cifs_sb, xid, server, ses, tcon);
3561 rc = mount_get_dfs_conns(ctx, cifs_sb, &xid, &server, &ses, &tcon);
3563 if (rc && !server && !ses) {
3564 /* Failed to connect. Try to connect to other targets in the referral. */
3565 rc = do_dfs_failover(ref_path + 1, full_path, cifs_sb, ctx, root_ses, &xid,
3566 &server, &ses, &tcon);
3568 if (rc == -EACCES || rc == -EOPNOTSUPP || !server || !ses)
3573 /* Make sure that requests go through new root servers */
3574 rc = is_referral_server(ref_path + 1, cifs_sb, tcon, &ref_server);
3578 set_root_ses(cifs_sb, &mount_id, ses, &root_ses);
3580 /* Get next dfs path and then continue chasing them if -EREMOTE */
3581 rc = next_dfs_prepath(cifs_sb, ctx, xid, server, tcon, &ref_path);
3582 /* Prevent recursion on broken link referrals */
3583 if (rc == -EREMOTE && ++count > MAX_NESTED_LINKS)
3585 } while (rc == -EREMOTE);
3587 if (rc || !tcon || !ses)
3592 * Store DFS full path in both superblock and tree connect structures.
3594 * For DFS root mounts, the prefix path (cifs_sb->prepath) is preserved during reconnect so
3595 * only the root path is set in cifs_sb->origin_fullpath and tcon->dfs_path. And for DFS
3596 * links, the prefix path is included in both and may be changed during reconnect. See
3597 * cifs_tree_connect().
3599 ref_path = dfs_cache_canonical_path(full_path, cifs_sb->local_nls, cifs_remap(cifs_sb));
3603 if (IS_ERR(ref_path)) {
3604 rc = PTR_ERR(ref_path);
3608 cifs_sb->origin_fullpath = ref_path;
3610 ref_path = kstrdup(cifs_sb->origin_fullpath, GFP_KERNEL);
3615 spin_lock(&cifs_tcp_ses_lock);
3616 tcon->dfs_path = ref_path;
3618 spin_unlock(&cifs_tcp_ses_lock);
3621 * After reconnecting to a different server, unique ids won't
3622 * match anymore, so we disable serverino. This prevents
3623 * dentry revalidation to think the dentry are stale (ESTALE).
3625 cifs_autodisable_serverino(cifs_sb);
3627 * Force the use of prefix path to support failover on DFS paths that
3628 * resolve to targets that have different prefix paths.
3630 cifs_sb->mnt_cifs_flags |= CIFS_MOUNT_USE_PREFIX_PATH;
3631 kfree(cifs_sb->prepath);
3632 cifs_sb->prepath = ctx->prepath;
3633 ctx->prepath = NULL;
3634 uuid_copy(&cifs_sb->dfs_mount_id, &mount_id);
3638 cifs_try_adding_channels(cifs_sb, ses);
3639 return mount_setup_tlink(cifs_sb, ses, tcon);
3644 kfree(cifs_sb->origin_fullpath);
3645 dfs_cache_put_refsrv_sessions(&mount_id);
3646 mount_put_conns(cifs_sb, xid, server, ses, tcon);
3650 int cifs_mount(struct cifs_sb_info *cifs_sb, struct smb3_fs_context *ctx)
3654 struct cifs_ses *ses;
3655 struct cifs_tcon *tcon;
3656 struct TCP_Server_Info *server;
3658 rc = mount_get_conns(ctx, cifs_sb, &xid, &server, &ses, &tcon);
3663 rc = is_path_remote(cifs_sb, ctx, xid, server, tcon);
3672 return mount_setup_tlink(cifs_sb, ses, tcon);
3675 mount_put_conns(cifs_sb, xid, server, ses, tcon);
3681 * Issue a TREE_CONNECT request.
3684 CIFSTCon(const unsigned int xid, struct cifs_ses *ses,
3685 const char *tree, struct cifs_tcon *tcon,
3686 const struct nls_table *nls_codepage)
3688 struct smb_hdr *smb_buffer;
3689 struct smb_hdr *smb_buffer_response;
3692 unsigned char *bcc_ptr;
3695 __u16 bytes_left, count;
3700 smb_buffer = cifs_buf_get();
3701 if (smb_buffer == NULL)
3704 smb_buffer_response = smb_buffer;
3706 header_assemble(smb_buffer, SMB_COM_TREE_CONNECT_ANDX,
3707 NULL /*no tid */ , 4 /*wct */ );
3709 smb_buffer->Mid = get_next_mid(ses->server);
3710 smb_buffer->Uid = ses->Suid;
3711 pSMB = (TCONX_REQ *) smb_buffer;
3712 pSMBr = (TCONX_RSP *) smb_buffer_response;
3714 pSMB->AndXCommand = 0xFF;
3715 pSMB->Flags = cpu_to_le16(TCON_EXTENDED_SECINFO);
3716 bcc_ptr = &pSMB->Password[0];
3717 if (tcon->pipe || (ses->server->sec_mode & SECMODE_USER)) {
3718 pSMB->PasswordLength = cpu_to_le16(1); /* minimum */
3719 *bcc_ptr = 0; /* password is null byte */
3720 bcc_ptr++; /* skip password */
3721 /* already aligned so no need to do it below */
3724 if (ses->server->sign)
3725 smb_buffer->Flags2 |= SMBFLG2_SECURITY_SIGNATURE;
3727 if (ses->capabilities & CAP_STATUS32) {
3728 smb_buffer->Flags2 |= SMBFLG2_ERR_STATUS;
3730 if (ses->capabilities & CAP_DFS) {
3731 smb_buffer->Flags2 |= SMBFLG2_DFS;
3733 if (ses->capabilities & CAP_UNICODE) {
3734 smb_buffer->Flags2 |= SMBFLG2_UNICODE;
3736 cifs_strtoUTF16((__le16 *) bcc_ptr, tree,
3737 6 /* max utf8 char length in bytes */ *
3738 (/* server len*/ + 256 /* share len */), nls_codepage);
3739 bcc_ptr += 2 * length; /* convert num 16 bit words to bytes */
3740 bcc_ptr += 2; /* skip trailing null */
3741 } else { /* ASCII */
3742 strcpy(bcc_ptr, tree);
3743 bcc_ptr += strlen(tree) + 1;
3745 strcpy(bcc_ptr, "?????");
3746 bcc_ptr += strlen("?????");
3748 count = bcc_ptr - &pSMB->Password[0];
3749 be32_add_cpu(&pSMB->hdr.smb_buf_length, count);
3750 pSMB->ByteCount = cpu_to_le16(count);
3752 rc = SendReceive(xid, ses, smb_buffer, smb_buffer_response, &length,
3755 /* above now done in SendReceive */
3759 tcon->tidStatus = CifsGood;
3760 tcon->need_reconnect = false;
3761 tcon->tid = smb_buffer_response->Tid;
3762 bcc_ptr = pByteArea(smb_buffer_response);
3763 bytes_left = get_bcc(smb_buffer_response);
3764 length = strnlen(bcc_ptr, bytes_left - 2);
3765 if (smb_buffer->Flags2 & SMBFLG2_UNICODE)
3771 /* skip service field (NB: this field is always ASCII) */
3773 if ((bcc_ptr[0] == 'I') && (bcc_ptr[1] == 'P') &&
3774 (bcc_ptr[2] == 'C')) {
3775 cifs_dbg(FYI, "IPC connection\n");
3779 } else if (length == 2) {
3780 if ((bcc_ptr[0] == 'A') && (bcc_ptr[1] == ':')) {
3781 /* the most common case */
3782 cifs_dbg(FYI, "disk share connection\n");
3785 bcc_ptr += length + 1;
3786 bytes_left -= (length + 1);
3787 strlcpy(tcon->treeName, tree, sizeof(tcon->treeName));
3789 /* mostly informational -- no need to fail on error here */
3790 kfree(tcon->nativeFileSystem);
3791 tcon->nativeFileSystem = cifs_strndup_from_utf16(bcc_ptr,
3792 bytes_left, is_unicode,
3795 cifs_dbg(FYI, "nativeFileSystem=%s\n", tcon->nativeFileSystem);
3797 if ((smb_buffer_response->WordCount == 3) ||
3798 (smb_buffer_response->WordCount == 7))
3799 /* field is in same location */
3800 tcon->Flags = le16_to_cpu(pSMBr->OptionalSupport);
3803 cifs_dbg(FYI, "Tcon flags: 0x%x\n", tcon->Flags);
3806 cifs_buf_release(smb_buffer);
3810 static void delayed_free(struct rcu_head *p)
3812 struct cifs_sb_info *cifs_sb = container_of(p, struct cifs_sb_info, rcu);
3814 unload_nls(cifs_sb->local_nls);
3815 smb3_cleanup_fs_context(cifs_sb->ctx);
3820 cifs_umount(struct cifs_sb_info *cifs_sb)
3822 struct rb_root *root = &cifs_sb->tlink_tree;
3823 struct rb_node *node;
3824 struct tcon_link *tlink;
3826 cancel_delayed_work_sync(&cifs_sb->prune_tlinks);
3828 spin_lock(&cifs_sb->tlink_tree_lock);
3829 while ((node = rb_first(root))) {
3830 tlink = rb_entry(node, struct tcon_link, tl_rbnode);
3831 cifs_get_tlink(tlink);
3832 clear_bit(TCON_LINK_IN_TREE, &tlink->tl_flags);
3833 rb_erase(node, root);
3835 spin_unlock(&cifs_sb->tlink_tree_lock);
3836 cifs_put_tlink(tlink);
3837 spin_lock(&cifs_sb->tlink_tree_lock);
3839 spin_unlock(&cifs_sb->tlink_tree_lock);
3841 kfree(cifs_sb->prepath);
3842 #ifdef CONFIG_CIFS_DFS_UPCALL
3843 dfs_cache_put_refsrv_sessions(&cifs_sb->dfs_mount_id);
3844 kfree(cifs_sb->origin_fullpath);
3846 call_rcu(&cifs_sb->rcu, delayed_free);
3850 cifs_negotiate_protocol(const unsigned int xid, struct cifs_ses *ses)
3853 struct TCP_Server_Info *server = cifs_ses_server(ses);
3855 if (!server->ops->need_neg || !server->ops->negotiate)
3858 /* only send once per connect */
3859 if (!server->ops->need_neg(server))
3862 rc = server->ops->negotiate(xid, ses);
3864 spin_lock(&GlobalMid_Lock);
3865 if (server->tcpStatus == CifsNeedNegotiate)
3866 server->tcpStatus = CifsGood;
3869 spin_unlock(&GlobalMid_Lock);
3876 cifs_setup_session(const unsigned int xid, struct cifs_ses *ses,
3877 struct nls_table *nls_info)
3880 struct TCP_Server_Info *server = cifs_ses_server(ses);
3882 if (!ses->binding) {
3883 ses->capabilities = server->capabilities;
3884 if (!linuxExtEnabled)
3885 ses->capabilities &= (~server->vals->cap_unix);
3887 if (ses->auth_key.response) {
3888 cifs_dbg(FYI, "Free previous auth_key.response = %p\n",
3889 ses->auth_key.response);
3890 kfree(ses->auth_key.response);
3891 ses->auth_key.response = NULL;
3892 ses->auth_key.len = 0;
3896 cifs_dbg(FYI, "Security Mode: 0x%x Capabilities: 0x%x TimeAdjust: %d\n",
3897 server->sec_mode, server->capabilities, server->timeAdj);
3899 if (server->ops->sess_setup)
3900 rc = server->ops->sess_setup(xid, ses, nls_info);
3903 cifs_server_dbg(VFS, "Send error in SessSetup = %d\n", rc);
3909 cifs_set_vol_auth(struct smb3_fs_context *ctx, struct cifs_ses *ses)
3911 ctx->sectype = ses->sectype;
3913 /* krb5 is special, since we don't need username or pw */
3914 if (ctx->sectype == Kerberos)
3917 return cifs_set_cifscreds(ctx, ses);
3920 static struct cifs_tcon *
3921 cifs_construct_tcon(struct cifs_sb_info *cifs_sb, kuid_t fsuid)
3924 struct cifs_tcon *master_tcon = cifs_sb_master_tcon(cifs_sb);
3925 struct cifs_ses *ses;
3926 struct cifs_tcon *tcon = NULL;
3927 struct smb3_fs_context *ctx;
3929 ctx = kzalloc(sizeof(*ctx), GFP_KERNEL);
3931 return ERR_PTR(-ENOMEM);
3933 ctx->local_nls = cifs_sb->local_nls;
3934 ctx->linux_uid = fsuid;
3935 ctx->cred_uid = fsuid;
3936 ctx->UNC = master_tcon->treeName;
3937 ctx->retry = master_tcon->retry;
3938 ctx->nocase = master_tcon->nocase;
3939 ctx->nohandlecache = master_tcon->nohandlecache;
3940 ctx->local_lease = master_tcon->local_lease;
3941 ctx->no_lease = master_tcon->no_lease;
3942 ctx->resilient = master_tcon->use_resilient;
3943 ctx->persistent = master_tcon->use_persistent;
3944 ctx->handle_timeout = master_tcon->handle_timeout;
3945 ctx->no_linux_ext = !master_tcon->unix_ext;
3946 ctx->linux_ext = master_tcon->posix_extensions;
3947 ctx->sectype = master_tcon->ses->sectype;
3948 ctx->sign = master_tcon->ses->sign;
3949 ctx->seal = master_tcon->seal;
3950 ctx->witness = master_tcon->use_witness;
3952 rc = cifs_set_vol_auth(ctx, master_tcon->ses);
3958 /* get a reference for the same TCP session */
3959 spin_lock(&cifs_tcp_ses_lock);
3960 ++master_tcon->ses->server->srv_count;
3961 spin_unlock(&cifs_tcp_ses_lock);
3963 ses = cifs_get_smb_ses(master_tcon->ses->server, ctx);
3965 tcon = (struct cifs_tcon *)ses;
3966 cifs_put_tcp_session(master_tcon->ses->server, 0);
3970 tcon = cifs_get_tcon(ses, ctx);
3972 cifs_put_smb_ses(ses);
3977 reset_cifs_unix_caps(0, tcon, NULL, ctx);
3980 kfree(ctx->username);
3981 kfree_sensitive(ctx->password);
3988 cifs_sb_master_tcon(struct cifs_sb_info *cifs_sb)
3990 return tlink_tcon(cifs_sb_master_tlink(cifs_sb));
3993 /* find and return a tlink with given uid */
3994 static struct tcon_link *
3995 tlink_rb_search(struct rb_root *root, kuid_t uid)
3997 struct rb_node *node = root->rb_node;
3998 struct tcon_link *tlink;
4001 tlink = rb_entry(node, struct tcon_link, tl_rbnode);
4003 if (uid_gt(tlink->tl_uid, uid))
4004 node = node->rb_left;
4005 else if (uid_lt(tlink->tl_uid, uid))
4006 node = node->rb_right;
4013 /* insert a tcon_link into the tree */
4015 tlink_rb_insert(struct rb_root *root, struct tcon_link *new_tlink)
4017 struct rb_node **new = &(root->rb_node), *parent = NULL;
4018 struct tcon_link *tlink;
4021 tlink = rb_entry(*new, struct tcon_link, tl_rbnode);
4024 if (uid_gt(tlink->tl_uid, new_tlink->tl_uid))
4025 new = &((*new)->rb_left);
4027 new = &((*new)->rb_right);
4030 rb_link_node(&new_tlink->tl_rbnode, parent, new);
4031 rb_insert_color(&new_tlink->tl_rbnode, root);
4035 * Find or construct an appropriate tcon given a cifs_sb and the fsuid of the
4038 * If the superblock doesn't refer to a multiuser mount, then just return
4039 * the master tcon for the mount.
4041 * First, search the rbtree for an existing tcon for this fsuid. If one
4042 * exists, then check to see if it's pending construction. If it is then wait
4043 * for construction to complete. Once it's no longer pending, check to see if
4044 * it failed and either return an error or retry construction, depending on
4047 * If one doesn't exist then insert a new tcon_link struct into the tree and
4048 * try to construct a new one.
4051 cifs_sb_tlink(struct cifs_sb_info *cifs_sb)
4054 kuid_t fsuid = current_fsuid();
4055 struct tcon_link *tlink, *newtlink;
4057 if (!(cifs_sb->mnt_cifs_flags & CIFS_MOUNT_MULTIUSER))
4058 return cifs_get_tlink(cifs_sb_master_tlink(cifs_sb));
4060 spin_lock(&cifs_sb->tlink_tree_lock);
4061 tlink = tlink_rb_search(&cifs_sb->tlink_tree, fsuid);
4063 cifs_get_tlink(tlink);
4064 spin_unlock(&cifs_sb->tlink_tree_lock);
4066 if (tlink == NULL) {
4067 newtlink = kzalloc(sizeof(*tlink), GFP_KERNEL);
4068 if (newtlink == NULL)
4069 return ERR_PTR(-ENOMEM);
4070 newtlink->tl_uid = fsuid;
4071 newtlink->tl_tcon = ERR_PTR(-EACCES);
4072 set_bit(TCON_LINK_PENDING, &newtlink->tl_flags);
4073 set_bit(TCON_LINK_IN_TREE, &newtlink->tl_flags);
4074 cifs_get_tlink(newtlink);
4076 spin_lock(&cifs_sb->tlink_tree_lock);
4077 /* was one inserted after previous search? */
4078 tlink = tlink_rb_search(&cifs_sb->tlink_tree, fsuid);
4080 cifs_get_tlink(tlink);
4081 spin_unlock(&cifs_sb->tlink_tree_lock);
4083 goto wait_for_construction;
4086 tlink_rb_insert(&cifs_sb->tlink_tree, tlink);
4087 spin_unlock(&cifs_sb->tlink_tree_lock);
4089 wait_for_construction:
4090 ret = wait_on_bit(&tlink->tl_flags, TCON_LINK_PENDING,
4091 TASK_INTERRUPTIBLE);
4093 cifs_put_tlink(tlink);
4094 return ERR_PTR(-ERESTARTSYS);
4097 /* if it's good, return it */
4098 if (!IS_ERR(tlink->tl_tcon))
4101 /* return error if we tried this already recently */
4102 if (time_before(jiffies, tlink->tl_time + TLINK_ERROR_EXPIRE)) {
4103 cifs_put_tlink(tlink);
4104 return ERR_PTR(-EACCES);
4107 if (test_and_set_bit(TCON_LINK_PENDING, &tlink->tl_flags))
4108 goto wait_for_construction;
4111 tlink->tl_tcon = cifs_construct_tcon(cifs_sb, fsuid);
4112 clear_bit(TCON_LINK_PENDING, &tlink->tl_flags);
4113 wake_up_bit(&tlink->tl_flags, TCON_LINK_PENDING);
4115 if (IS_ERR(tlink->tl_tcon)) {
4116 cifs_put_tlink(tlink);
4117 return ERR_PTR(-EACCES);
4124 * periodic workqueue job that scans tcon_tree for a superblock and closes
4128 cifs_prune_tlinks(struct work_struct *work)
4130 struct cifs_sb_info *cifs_sb = container_of(work, struct cifs_sb_info,
4132 struct rb_root *root = &cifs_sb->tlink_tree;
4133 struct rb_node *node;
4134 struct rb_node *tmp;
4135 struct tcon_link *tlink;
4138 * Because we drop the spinlock in the loop in order to put the tlink
4139 * it's not guarded against removal of links from the tree. The only
4140 * places that remove entries from the tree are this function and
4141 * umounts. Because this function is non-reentrant and is canceled
4142 * before umount can proceed, this is safe.
4144 spin_lock(&cifs_sb->tlink_tree_lock);
4145 node = rb_first(root);
4146 while (node != NULL) {
4148 node = rb_next(tmp);
4149 tlink = rb_entry(tmp, struct tcon_link, tl_rbnode);
4151 if (test_bit(TCON_LINK_MASTER, &tlink->tl_flags) ||
4152 atomic_read(&tlink->tl_count) != 0 ||
4153 time_after(tlink->tl_time + TLINK_IDLE_EXPIRE, jiffies))
4156 cifs_get_tlink(tlink);
4157 clear_bit(TCON_LINK_IN_TREE, &tlink->tl_flags);
4158 rb_erase(tmp, root);
4160 spin_unlock(&cifs_sb->tlink_tree_lock);
4161 cifs_put_tlink(tlink);
4162 spin_lock(&cifs_sb->tlink_tree_lock);
4164 spin_unlock(&cifs_sb->tlink_tree_lock);
4166 queue_delayed_work(cifsiod_wq, &cifs_sb->prune_tlinks,
4170 #ifdef CONFIG_CIFS_DFS_UPCALL
4171 int cifs_tree_connect(const unsigned int xid, struct cifs_tcon *tcon, const struct nls_table *nlsc)
4174 struct TCP_Server_Info *server = tcon->ses->server;
4175 const struct smb_version_operations *ops = server->ops;
4176 struct dfs_cache_tgt_list tl;
4177 struct dfs_cache_tgt_iterator *it = NULL;
4179 const char *tcp_host;
4180 size_t tcp_host_len;
4181 const char *dfs_host;
4182 size_t dfs_host_len;
4183 char *share = NULL, *prefix = NULL;
4184 struct dfs_info3_param ref = {0};
4187 tree = kzalloc(MAX_TREE_SIZE, GFP_KERNEL);
4191 /* If it is not dfs or there was no cached dfs referral, then reconnect to same share */
4192 if (!tcon->dfs_path || dfs_cache_noreq_find(tcon->dfs_path + 1, &ref, &tl)) {
4194 scnprintf(tree, MAX_TREE_SIZE, "\\\\%s\\IPC$", server->hostname);
4195 rc = ops->tree_connect(xid, tcon->ses, tree, tcon, nlsc);
4197 rc = ops->tree_connect(xid, tcon->ses, tcon->treeName, tcon, nlsc);
4202 isroot = ref.server_type == DFS_TYPE_ROOT;
4203 free_dfs_info_param(&ref);
4205 extract_unc_hostname(server->hostname, &tcp_host, &tcp_host_len);
4207 for (it = dfs_cache_get_tgt_iterator(&tl); it; it = dfs_cache_get_next_tgt(&tl, it)) {
4215 rc = dfs_cache_get_tgt_share(tcon->dfs_path + 1, it, &share, &prefix);
4217 cifs_dbg(VFS, "%s: failed to parse target share %d\n",
4222 extract_unc_hostname(share, &dfs_host, &dfs_host_len);
4224 if (dfs_host_len != tcp_host_len
4225 || strncasecmp(dfs_host, tcp_host, dfs_host_len) != 0) {
4226 cifs_dbg(FYI, "%s: %.*s doesn't match %.*s\n", __func__, (int)dfs_host_len,
4227 dfs_host, (int)tcp_host_len, tcp_host);
4229 rc = match_target_ip(server, dfs_host, dfs_host_len, &target_match);
4231 cifs_dbg(VFS, "%s: failed to match target ip: %d\n", __func__, rc);
4235 if (!target_match) {
4236 cifs_dbg(FYI, "%s: skipping target\n", __func__);
4242 scnprintf(tree, MAX_TREE_SIZE, "\\\\%s\\IPC$", share);
4243 rc = ops->tree_connect(xid, tcon->ses, tree, tcon, nlsc);
4245 scnprintf(tree, MAX_TREE_SIZE, "\\%s", share);
4246 rc = ops->tree_connect(xid, tcon->ses, tree, tcon, nlsc);
4247 /* Only handle prefix paths of DFS link targets */
4248 if (!rc && !isroot) {
4249 rc = update_super_prepath(tcon, prefix);
4262 rc = dfs_cache_noreq_update_tgthint(tcon->dfs_path + 1, it);
4266 dfs_cache_free_tgts(&tl);
4272 int cifs_tree_connect(const unsigned int xid, struct cifs_tcon *tcon, const struct nls_table *nlsc)
4274 const struct smb_version_operations *ops = tcon->ses->server->ops;
4276 return ops->tree_connect(xid, tcon->ses, tcon->treeName, tcon, nlsc);