Linux kernel mirror (for testing)
git.kernel.org/pub/scm/linux/kernel/git/torvalds/linux.git
kernel
os
linux
fork
Configure Feed
Select the types of activity you want to include in your feed.
1// SPDX-License-Identifier: LGPL-2.1
2/*
3 *
4 * Copyright (C) International Business Machines Corp., 2002,2011
5 * Author(s): Steve French (sfrench@us.ibm.com)
6 *
7 */
8#include <linux/fs.h>
9#include <linux/net.h>
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>
32#include <net/ipv6.h>
33#include <linux/parser.h>
34#include <linux/bvec.h>
35#include "cifspdu.h"
36#include "cifsglob.h"
37#include "cifsproto.h"
38#include "cifs_unicode.h"
39#include "cifs_debug.h"
40#include "cifs_fs_sb.h"
41#include "ntlmssp.h"
42#include "nterr.h"
43#include "rfc1002pdu.h"
44#include "fscache.h"
45#include "smb2proto.h"
46#include "smbdirect.h"
47#include "dns_resolve.h"
48#ifdef CONFIG_CIFS_DFS_UPCALL
49#include "dfs.h"
50#include "dfs_cache.h"
51#endif
52#include "fs_context.h"
53#include "cifs_swn.h"
54
55extern mempool_t *cifs_req_poolp;
56extern bool disable_legacy_dialects;
57
58/* FIXME: should these be tunable? */
59#define TLINK_ERROR_EXPIRE (1 * HZ)
60#define TLINK_IDLE_EXPIRE (600 * HZ)
61
62/* Drop the connection to not overload the server */
63#define MAX_STATUS_IO_TIMEOUT 5
64
65static int ip_connect(struct TCP_Server_Info *server);
66static int generic_ip_connect(struct TCP_Server_Info *server);
67static void tlink_rb_insert(struct rb_root *root, struct tcon_link *new_tlink);
68static void cifs_prune_tlinks(struct work_struct *work);
69
70/*
71 * Resolve hostname and set ip addr in tcp ses. Useful for hostnames that may
72 * get their ip addresses changed at some point.
73 *
74 * This should be called with server->srv_mutex held.
75 */
76static int reconn_set_ipaddr_from_hostname(struct TCP_Server_Info *server)
77{
78 int rc;
79 int len;
80 char *unc;
81 struct sockaddr_storage ss;
82
83 if (!server->hostname)
84 return -EINVAL;
85
86 /* if server hostname isn't populated, there's nothing to do here */
87 if (server->hostname[0] == '\0')
88 return 0;
89
90 len = strlen(server->hostname) + 3;
91
92 unc = kmalloc(len, GFP_KERNEL);
93 if (!unc) {
94 cifs_dbg(FYI, "%s: failed to create UNC path\n", __func__);
95 return -ENOMEM;
96 }
97 scnprintf(unc, len, "\\\\%s", server->hostname);
98
99 spin_lock(&server->srv_lock);
100 ss = server->dstaddr;
101 spin_unlock(&server->srv_lock);
102
103 rc = dns_resolve_server_name_to_ip(unc, (struct sockaddr *)&ss, NULL);
104 kfree(unc);
105
106 if (rc < 0) {
107 cifs_dbg(FYI, "%s: failed to resolve server part of %s to IP: %d\n",
108 __func__, server->hostname, rc);
109 } else {
110 spin_lock(&server->srv_lock);
111 memcpy(&server->dstaddr, &ss, sizeof(server->dstaddr));
112 spin_unlock(&server->srv_lock);
113 rc = 0;
114 }
115
116 return rc;
117}
118
119static void smb2_query_server_interfaces(struct work_struct *work)
120{
121 int rc;
122 int xid;
123 struct cifs_tcon *tcon = container_of(work,
124 struct cifs_tcon,
125 query_interfaces.work);
126
127 /*
128 * query server network interfaces, in case they change
129 */
130 xid = get_xid();
131 rc = SMB3_request_interfaces(xid, tcon, false);
132 free_xid(xid);
133
134 if (rc) {
135 if (rc == -EOPNOTSUPP)
136 return;
137
138 cifs_dbg(FYI, "%s: failed to query server interfaces: %d\n",
139 __func__, rc);
140 }
141
142 queue_delayed_work(cifsiod_wq, &tcon->query_interfaces,
143 (SMB_INTERFACE_POLL_INTERVAL * HZ));
144}
145
146/*
147 * Update the tcpStatus for the server.
148 * This is used to signal the cifsd thread to call cifs_reconnect
149 * ONLY cifsd thread should call cifs_reconnect. For any other
150 * thread, use this function
151 *
152 * @server: the tcp ses for which reconnect is needed
153 * @all_channels: if this needs to be done for all channels
154 */
155void
156cifs_signal_cifsd_for_reconnect(struct TCP_Server_Info *server,
157 bool all_channels)
158{
159 struct TCP_Server_Info *pserver;
160 struct cifs_ses *ses;
161 int i;
162
163 /* If server is a channel, select the primary channel */
164 pserver = SERVER_IS_CHAN(server) ? server->primary_server : server;
165
166 /* if we need to signal just this channel */
167 if (!all_channels) {
168 spin_lock(&server->srv_lock);
169 if (server->tcpStatus != CifsExiting)
170 server->tcpStatus = CifsNeedReconnect;
171 spin_unlock(&server->srv_lock);
172 return;
173 }
174
175 spin_lock(&cifs_tcp_ses_lock);
176 list_for_each_entry(ses, &pserver->smb_ses_list, smb_ses_list) {
177 spin_lock(&ses->chan_lock);
178 for (i = 0; i < ses->chan_count; i++) {
179 if (!ses->chans[i].server)
180 continue;
181
182 spin_lock(&ses->chans[i].server->srv_lock);
183 if (ses->chans[i].server->tcpStatus != CifsExiting)
184 ses->chans[i].server->tcpStatus = CifsNeedReconnect;
185 spin_unlock(&ses->chans[i].server->srv_lock);
186 }
187 spin_unlock(&ses->chan_lock);
188 }
189 spin_unlock(&cifs_tcp_ses_lock);
190}
191
192/*
193 * Mark all sessions and tcons for reconnect.
194 * IMPORTANT: make sure that this gets called only from
195 * cifsd thread. For any other thread, use
196 * cifs_signal_cifsd_for_reconnect
197 *
198 * @server: the tcp ses for which reconnect is needed
199 * @server needs to be previously set to CifsNeedReconnect.
200 * @mark_smb_session: whether even sessions need to be marked
201 */
202void
203cifs_mark_tcp_ses_conns_for_reconnect(struct TCP_Server_Info *server,
204 bool mark_smb_session)
205{
206 struct TCP_Server_Info *pserver;
207 struct cifs_ses *ses, *nses;
208 struct cifs_tcon *tcon;
209
210 /*
211 * before reconnecting the tcp session, mark the smb session (uid) and the tid bad so they
212 * are not used until reconnected.
213 */
214 cifs_dbg(FYI, "%s: marking necessary sessions and tcons for reconnect\n", __func__);
215
216 /* If server is a channel, select the primary channel */
217 pserver = SERVER_IS_CHAN(server) ? server->primary_server : server;
218
219 /*
220 * if the server has been marked for termination, there is a
221 * chance that the remaining channels all need reconnect. To be
222 * on the safer side, mark the session and trees for reconnect
223 * for this scenario. This might cause a few redundant session
224 * setup and tree connect requests, but it is better than not doing
225 * a tree connect when needed, and all following requests failing
226 */
227 if (server->terminate) {
228 mark_smb_session = true;
229 server = pserver;
230 }
231
232 spin_lock(&cifs_tcp_ses_lock);
233 list_for_each_entry_safe(ses, nses, &pserver->smb_ses_list, smb_ses_list) {
234 /* check if iface is still active */
235 spin_lock(&ses->chan_lock);
236 if (!cifs_chan_is_iface_active(ses, server)) {
237 spin_unlock(&ses->chan_lock);
238 cifs_chan_update_iface(ses, server);
239 spin_lock(&ses->chan_lock);
240 }
241
242 if (!mark_smb_session && cifs_chan_needs_reconnect(ses, server)) {
243 spin_unlock(&ses->chan_lock);
244 continue;
245 }
246
247 if (mark_smb_session)
248 CIFS_SET_ALL_CHANS_NEED_RECONNECT(ses);
249 else
250 cifs_chan_set_need_reconnect(ses, server);
251
252 cifs_dbg(FYI, "%s: channel connect bitmap: 0x%lx\n",
253 __func__, ses->chans_need_reconnect);
254
255 /* If all channels need reconnect, then tcon needs reconnect */
256 if (!mark_smb_session && !CIFS_ALL_CHANS_NEED_RECONNECT(ses)) {
257 spin_unlock(&ses->chan_lock);
258 continue;
259 }
260 spin_unlock(&ses->chan_lock);
261
262 spin_lock(&ses->ses_lock);
263 ses->ses_status = SES_NEED_RECON;
264 spin_unlock(&ses->ses_lock);
265
266 list_for_each_entry(tcon, &ses->tcon_list, tcon_list) {
267 tcon->need_reconnect = true;
268 spin_lock(&tcon->tc_lock);
269 tcon->status = TID_NEED_RECON;
270 spin_unlock(&tcon->tc_lock);
271
272 cancel_delayed_work(&tcon->query_interfaces);
273 }
274 if (ses->tcon_ipc) {
275 ses->tcon_ipc->need_reconnect = true;
276 spin_lock(&ses->tcon_ipc->tc_lock);
277 ses->tcon_ipc->status = TID_NEED_RECON;
278 spin_unlock(&ses->tcon_ipc->tc_lock);
279 }
280 }
281 spin_unlock(&cifs_tcp_ses_lock);
282}
283
284static void
285cifs_abort_connection(struct TCP_Server_Info *server)
286{
287 struct mid_q_entry *mid, *nmid;
288 struct list_head retry_list;
289
290 server->maxBuf = 0;
291 server->max_read = 0;
292
293 /* do not want to be sending data on a socket we are freeing */
294 cifs_dbg(FYI, "%s: tearing down socket\n", __func__);
295 cifs_server_lock(server);
296 if (server->ssocket) {
297 cifs_dbg(FYI, "State: 0x%x Flags: 0x%lx\n", server->ssocket->state,
298 server->ssocket->flags);
299 kernel_sock_shutdown(server->ssocket, SHUT_WR);
300 cifs_dbg(FYI, "Post shutdown state: 0x%x Flags: 0x%lx\n", server->ssocket->state,
301 server->ssocket->flags);
302 sock_release(server->ssocket);
303 server->ssocket = NULL;
304 }
305 server->sequence_number = 0;
306 server->session_estab = false;
307 kfree_sensitive(server->session_key.response);
308 server->session_key.response = NULL;
309 server->session_key.len = 0;
310 server->lstrp = jiffies;
311
312 /* mark submitted MIDs for retry and issue callback */
313 INIT_LIST_HEAD(&retry_list);
314 cifs_dbg(FYI, "%s: moving mids to private list\n", __func__);
315 spin_lock(&server->mid_lock);
316 list_for_each_entry_safe(mid, nmid, &server->pending_mid_q, qhead) {
317 kref_get(&mid->refcount);
318 if (mid->mid_state == MID_REQUEST_SUBMITTED)
319 mid->mid_state = MID_RETRY_NEEDED;
320 list_move(&mid->qhead, &retry_list);
321 mid->mid_flags |= MID_DELETED;
322 }
323 spin_unlock(&server->mid_lock);
324 cifs_server_unlock(server);
325
326 cifs_dbg(FYI, "%s: issuing mid callbacks\n", __func__);
327 list_for_each_entry_safe(mid, nmid, &retry_list, qhead) {
328 list_del_init(&mid->qhead);
329 mid->callback(mid);
330 release_mid(mid);
331 }
332
333 if (cifs_rdma_enabled(server)) {
334 cifs_server_lock(server);
335 smbd_destroy(server);
336 cifs_server_unlock(server);
337 }
338}
339
340static bool cifs_tcp_ses_needs_reconnect(struct TCP_Server_Info *server, int num_targets)
341{
342 spin_lock(&server->srv_lock);
343 server->nr_targets = num_targets;
344 if (server->tcpStatus == CifsExiting) {
345 /* the demux thread will exit normally next time through the loop */
346 spin_unlock(&server->srv_lock);
347 wake_up(&server->response_q);
348 return false;
349 }
350
351 cifs_dbg(FYI, "Mark tcp session as need reconnect\n");
352 trace_smb3_reconnect(server->CurrentMid, server->conn_id,
353 server->hostname);
354 server->tcpStatus = CifsNeedReconnect;
355
356 spin_unlock(&server->srv_lock);
357 return true;
358}
359
360/*
361 * cifs tcp session reconnection
362 *
363 * mark tcp session as reconnecting so temporarily locked
364 * mark all smb sessions as reconnecting for tcp session
365 * reconnect tcp session
366 * wake up waiters on reconnection? - (not needed currently)
367 *
368 * if mark_smb_session is passed as true, unconditionally mark
369 * the smb session (and tcon) for reconnect as well. This value
370 * doesn't really matter for non-multichannel scenario.
371 *
372 */
373static int __cifs_reconnect(struct TCP_Server_Info *server,
374 bool mark_smb_session)
375{
376 int rc = 0;
377
378 if (!cifs_tcp_ses_needs_reconnect(server, 1))
379 return 0;
380
381 cifs_mark_tcp_ses_conns_for_reconnect(server, mark_smb_session);
382
383 cifs_abort_connection(server);
384
385 do {
386 try_to_freeze();
387 cifs_server_lock(server);
388
389 if (!cifs_swn_set_server_dstaddr(server)) {
390 /* resolve the hostname again to make sure that IP address is up-to-date */
391 rc = reconn_set_ipaddr_from_hostname(server);
392 cifs_dbg(FYI, "%s: reconn_set_ipaddr_from_hostname: rc=%d\n", __func__, rc);
393 }
394
395 if (cifs_rdma_enabled(server))
396 rc = smbd_reconnect(server);
397 else
398 rc = generic_ip_connect(server);
399 if (rc) {
400 cifs_server_unlock(server);
401 cifs_dbg(FYI, "%s: reconnect error %d\n", __func__, rc);
402 msleep(3000);
403 } else {
404 atomic_inc(&tcpSesReconnectCount);
405 set_credits(server, 1);
406 spin_lock(&server->srv_lock);
407 if (server->tcpStatus != CifsExiting)
408 server->tcpStatus = CifsNeedNegotiate;
409 spin_unlock(&server->srv_lock);
410 cifs_swn_reset_server_dstaddr(server);
411 cifs_server_unlock(server);
412 mod_delayed_work(cifsiod_wq, &server->reconnect, 0);
413 }
414 } while (server->tcpStatus == CifsNeedReconnect);
415
416 spin_lock(&server->srv_lock);
417 if (server->tcpStatus == CifsNeedNegotiate)
418 mod_delayed_work(cifsiod_wq, &server->echo, 0);
419 spin_unlock(&server->srv_lock);
420
421 wake_up(&server->response_q);
422 return rc;
423}
424
425#ifdef CONFIG_CIFS_DFS_UPCALL
426static int __reconnect_target_unlocked(struct TCP_Server_Info *server, const char *target)
427{
428 int rc;
429 char *hostname;
430
431 if (!cifs_swn_set_server_dstaddr(server)) {
432 if (server->hostname != target) {
433 hostname = extract_hostname(target);
434 if (!IS_ERR(hostname)) {
435 spin_lock(&server->srv_lock);
436 kfree(server->hostname);
437 server->hostname = hostname;
438 spin_unlock(&server->srv_lock);
439 } else {
440 cifs_dbg(FYI, "%s: couldn't extract hostname or address from dfs target: %ld\n",
441 __func__, PTR_ERR(hostname));
442 cifs_dbg(FYI, "%s: default to last target server: %s\n", __func__,
443 server->hostname);
444 }
445 }
446 /* resolve the hostname again to make sure that IP address is up-to-date. */
447 rc = reconn_set_ipaddr_from_hostname(server);
448 cifs_dbg(FYI, "%s: reconn_set_ipaddr_from_hostname: rc=%d\n", __func__, rc);
449 }
450 /* Reconnect the socket */
451 if (cifs_rdma_enabled(server))
452 rc = smbd_reconnect(server);
453 else
454 rc = generic_ip_connect(server);
455
456 return rc;
457}
458
459static int reconnect_target_unlocked(struct TCP_Server_Info *server, struct dfs_cache_tgt_list *tl,
460 struct dfs_cache_tgt_iterator **target_hint)
461{
462 int rc;
463 struct dfs_cache_tgt_iterator *tit;
464
465 *target_hint = NULL;
466
467 /* If dfs target list is empty, then reconnect to last server */
468 tit = dfs_cache_get_tgt_iterator(tl);
469 if (!tit)
470 return __reconnect_target_unlocked(server, server->hostname);
471
472 /* Otherwise, try every dfs target in @tl */
473 for (; tit; tit = dfs_cache_get_next_tgt(tl, tit)) {
474 rc = __reconnect_target_unlocked(server, dfs_cache_get_tgt_name(tit));
475 if (!rc) {
476 *target_hint = tit;
477 break;
478 }
479 }
480 return rc;
481}
482
483static int reconnect_dfs_server(struct TCP_Server_Info *server)
484{
485 struct dfs_cache_tgt_iterator *target_hint = NULL;
486
487 DFS_CACHE_TGT_LIST(tl);
488 int num_targets = 0;
489 int rc = 0;
490
491 /*
492 * Determine the number of dfs targets the referral path in @cifs_sb resolves to.
493 *
494 * smb2_reconnect() needs to know how long it should wait based upon the number of dfs
495 * targets (server->nr_targets). It's also possible that the cached referral was cleared
496 * through /proc/fs/cifs/dfscache or the target list is empty due to server settings after
497 * refreshing the referral, so, in this case, default it to 1.
498 */
499 mutex_lock(&server->refpath_lock);
500 if (!dfs_cache_noreq_find(server->leaf_fullpath + 1, NULL, &tl))
501 num_targets = dfs_cache_get_nr_tgts(&tl);
502 mutex_unlock(&server->refpath_lock);
503 if (!num_targets)
504 num_targets = 1;
505
506 if (!cifs_tcp_ses_needs_reconnect(server, num_targets))
507 return 0;
508
509 /*
510 * Unconditionally mark all sessions & tcons for reconnect as we might be connecting to a
511 * different server or share during failover. It could be improved by adding some logic to
512 * only do that in case it connects to a different server or share, though.
513 */
514 cifs_mark_tcp_ses_conns_for_reconnect(server, true);
515
516 cifs_abort_connection(server);
517
518 do {
519 try_to_freeze();
520 cifs_server_lock(server);
521
522 rc = reconnect_target_unlocked(server, &tl, &target_hint);
523 if (rc) {
524 /* Failed to reconnect socket */
525 cifs_server_unlock(server);
526 cifs_dbg(FYI, "%s: reconnect error %d\n", __func__, rc);
527 msleep(3000);
528 continue;
529 }
530 /*
531 * Socket was created. Update tcp session status to CifsNeedNegotiate so that a
532 * process waiting for reconnect will know it needs to re-establish session and tcon
533 * through the reconnected target server.
534 */
535 atomic_inc(&tcpSesReconnectCount);
536 set_credits(server, 1);
537 spin_lock(&server->srv_lock);
538 if (server->tcpStatus != CifsExiting)
539 server->tcpStatus = CifsNeedNegotiate;
540 spin_unlock(&server->srv_lock);
541 cifs_swn_reset_server_dstaddr(server);
542 cifs_server_unlock(server);
543 mod_delayed_work(cifsiod_wq, &server->reconnect, 0);
544 } while (server->tcpStatus == CifsNeedReconnect);
545
546 mutex_lock(&server->refpath_lock);
547 dfs_cache_noreq_update_tgthint(server->leaf_fullpath + 1, target_hint);
548 mutex_unlock(&server->refpath_lock);
549 dfs_cache_free_tgts(&tl);
550
551 /* Need to set up echo worker again once connection has been established */
552 spin_lock(&server->srv_lock);
553 if (server->tcpStatus == CifsNeedNegotiate)
554 mod_delayed_work(cifsiod_wq, &server->echo, 0);
555 spin_unlock(&server->srv_lock);
556
557 wake_up(&server->response_q);
558 return rc;
559}
560
561int cifs_reconnect(struct TCP_Server_Info *server, bool mark_smb_session)
562{
563 mutex_lock(&server->refpath_lock);
564 if (!server->leaf_fullpath) {
565 mutex_unlock(&server->refpath_lock);
566 return __cifs_reconnect(server, mark_smb_session);
567 }
568 mutex_unlock(&server->refpath_lock);
569
570 return reconnect_dfs_server(server);
571}
572#else
573int cifs_reconnect(struct TCP_Server_Info *server, bool mark_smb_session)
574{
575 return __cifs_reconnect(server, mark_smb_session);
576}
577#endif
578
579static void
580cifs_echo_request(struct work_struct *work)
581{
582 int rc;
583 struct TCP_Server_Info *server = container_of(work,
584 struct TCP_Server_Info, echo.work);
585
586 /*
587 * We cannot send an echo if it is disabled.
588 * Also, no need to ping if we got a response recently.
589 */
590
591 if (server->tcpStatus == CifsNeedReconnect ||
592 server->tcpStatus == CifsExiting ||
593 server->tcpStatus == CifsNew ||
594 (server->ops->can_echo && !server->ops->can_echo(server)) ||
595 time_before(jiffies, server->lstrp + server->echo_interval - HZ))
596 goto requeue_echo;
597
598 rc = server->ops->echo ? server->ops->echo(server) : -ENOSYS;
599 cifs_server_dbg(FYI, "send echo request: rc = %d\n", rc);
600
601 /* Check witness registrations */
602 cifs_swn_check();
603
604requeue_echo:
605 queue_delayed_work(cifsiod_wq, &server->echo, server->echo_interval);
606}
607
608static bool
609allocate_buffers(struct TCP_Server_Info *server)
610{
611 if (!server->bigbuf) {
612 server->bigbuf = (char *)cifs_buf_get();
613 if (!server->bigbuf) {
614 cifs_server_dbg(VFS, "No memory for large SMB response\n");
615 msleep(3000);
616 /* retry will check if exiting */
617 return false;
618 }
619 } else if (server->large_buf) {
620 /* we are reusing a dirty large buf, clear its start */
621 memset(server->bigbuf, 0, HEADER_SIZE(server));
622 }
623
624 if (!server->smallbuf) {
625 server->smallbuf = (char *)cifs_small_buf_get();
626 if (!server->smallbuf) {
627 cifs_server_dbg(VFS, "No memory for SMB response\n");
628 msleep(1000);
629 /* retry will check if exiting */
630 return false;
631 }
632 /* beginning of smb buffer is cleared in our buf_get */
633 } else {
634 /* if existing small buf clear beginning */
635 memset(server->smallbuf, 0, HEADER_SIZE(server));
636 }
637
638 return true;
639}
640
641static bool
642server_unresponsive(struct TCP_Server_Info *server)
643{
644 /*
645 * We need to wait 3 echo intervals to make sure we handle such
646 * situations right:
647 * 1s client sends a normal SMB request
648 * 2s client gets a response
649 * 30s echo workqueue job pops, and decides we got a response recently
650 * and don't need to send another
651 * ...
652 * 65s kernel_recvmsg times out, and we see that we haven't gotten
653 * a response in >60s.
654 */
655 spin_lock(&server->srv_lock);
656 if ((server->tcpStatus == CifsGood ||
657 server->tcpStatus == CifsNeedNegotiate) &&
658 (!server->ops->can_echo || server->ops->can_echo(server)) &&
659 time_after(jiffies, server->lstrp + 3 * server->echo_interval)) {
660 spin_unlock(&server->srv_lock);
661 cifs_server_dbg(VFS, "has not responded in %lu seconds. Reconnecting...\n",
662 (3 * server->echo_interval) / HZ);
663 cifs_reconnect(server, false);
664 return true;
665 }
666 spin_unlock(&server->srv_lock);
667
668 return false;
669}
670
671static inline bool
672zero_credits(struct TCP_Server_Info *server)
673{
674 int val;
675
676 spin_lock(&server->req_lock);
677 val = server->credits + server->echo_credits + server->oplock_credits;
678 if (server->in_flight == 0 && val == 0) {
679 spin_unlock(&server->req_lock);
680 return true;
681 }
682 spin_unlock(&server->req_lock);
683 return false;
684}
685
686static int
687cifs_readv_from_socket(struct TCP_Server_Info *server, struct msghdr *smb_msg)
688{
689 int length = 0;
690 int total_read;
691
692 for (total_read = 0; msg_data_left(smb_msg); total_read += length) {
693 try_to_freeze();
694
695 /* reconnect if no credits and no requests in flight */
696 if (zero_credits(server)) {
697 cifs_reconnect(server, false);
698 return -ECONNABORTED;
699 }
700
701 if (server_unresponsive(server))
702 return -ECONNABORTED;
703 if (cifs_rdma_enabled(server) && server->smbd_conn)
704 length = smbd_recv(server->smbd_conn, smb_msg);
705 else
706 length = sock_recvmsg(server->ssocket, smb_msg, 0);
707
708 spin_lock(&server->srv_lock);
709 if (server->tcpStatus == CifsExiting) {
710 spin_unlock(&server->srv_lock);
711 return -ESHUTDOWN;
712 }
713
714 if (server->tcpStatus == CifsNeedReconnect) {
715 spin_unlock(&server->srv_lock);
716 cifs_reconnect(server, false);
717 return -ECONNABORTED;
718 }
719 spin_unlock(&server->srv_lock);
720
721 if (length == -ERESTARTSYS ||
722 length == -EAGAIN ||
723 length == -EINTR) {
724 /*
725 * Minimum sleep to prevent looping, allowing socket
726 * to clear and app threads to set tcpStatus
727 * CifsNeedReconnect if server hung.
728 */
729 usleep_range(1000, 2000);
730 length = 0;
731 continue;
732 }
733
734 if (length <= 0) {
735 cifs_dbg(FYI, "Received no data or error: %d\n", length);
736 cifs_reconnect(server, false);
737 return -ECONNABORTED;
738 }
739 }
740 return total_read;
741}
742
743int
744cifs_read_from_socket(struct TCP_Server_Info *server, char *buf,
745 unsigned int to_read)
746{
747 struct msghdr smb_msg = {};
748 struct kvec iov = {.iov_base = buf, .iov_len = to_read};
749
750 iov_iter_kvec(&smb_msg.msg_iter, ITER_DEST, &iov, 1, to_read);
751
752 return cifs_readv_from_socket(server, &smb_msg);
753}
754
755ssize_t
756cifs_discard_from_socket(struct TCP_Server_Info *server, size_t to_read)
757{
758 struct msghdr smb_msg = {};
759
760 /*
761 * iov_iter_discard already sets smb_msg.type and count and iov_offset
762 * and cifs_readv_from_socket sets msg_control and msg_controllen
763 * so little to initialize in struct msghdr
764 */
765 iov_iter_discard(&smb_msg.msg_iter, ITER_DEST, to_read);
766
767 return cifs_readv_from_socket(server, &smb_msg);
768}
769
770int
771cifs_read_page_from_socket(struct TCP_Server_Info *server, struct page *page,
772 unsigned int page_offset, unsigned int to_read)
773{
774 struct msghdr smb_msg = {};
775 struct bio_vec bv;
776
777 bvec_set_page(&bv, page, to_read, page_offset);
778 iov_iter_bvec(&smb_msg.msg_iter, ITER_DEST, &bv, 1, to_read);
779 return cifs_readv_from_socket(server, &smb_msg);
780}
781
782int
783cifs_read_iter_from_socket(struct TCP_Server_Info *server, struct iov_iter *iter,
784 unsigned int to_read)
785{
786 struct msghdr smb_msg = { .msg_iter = *iter };
787 int ret;
788
789 iov_iter_truncate(&smb_msg.msg_iter, to_read);
790 ret = cifs_readv_from_socket(server, &smb_msg);
791 if (ret > 0)
792 iov_iter_advance(iter, ret);
793 return ret;
794}
795
796static bool
797is_smb_response(struct TCP_Server_Info *server, unsigned char type)
798{
799 /*
800 * The first byte big endian of the length field,
801 * is actually not part of the length but the type
802 * with the most common, zero, as regular data.
803 */
804 switch (type) {
805 case RFC1002_SESSION_MESSAGE:
806 /* Regular SMB response */
807 return true;
808 case RFC1002_SESSION_KEEP_ALIVE:
809 cifs_dbg(FYI, "RFC 1002 session keep alive\n");
810 break;
811 case RFC1002_POSITIVE_SESSION_RESPONSE:
812 cifs_dbg(FYI, "RFC 1002 positive session response\n");
813 break;
814 case RFC1002_NEGATIVE_SESSION_RESPONSE:
815 /*
816 * We get this from Windows 98 instead of an error on
817 * SMB negprot response.
818 */
819 cifs_dbg(FYI, "RFC 1002 negative session response\n");
820 /* give server a second to clean up */
821 msleep(1000);
822 /*
823 * Always try 445 first on reconnect since we get NACK
824 * on some if we ever connected to port 139 (the NACK
825 * is since we do not begin with RFC1001 session
826 * initialize frame).
827 */
828 cifs_set_port((struct sockaddr *)&server->dstaddr, CIFS_PORT);
829 cifs_reconnect(server, true);
830 break;
831 default:
832 cifs_server_dbg(VFS, "RFC 1002 unknown response type 0x%x\n", type);
833 cifs_reconnect(server, true);
834 }
835
836 return false;
837}
838
839void
840dequeue_mid(struct mid_q_entry *mid, bool malformed)
841{
842#ifdef CONFIG_CIFS_STATS2
843 mid->when_received = jiffies;
844#endif
845 spin_lock(&mid->server->mid_lock);
846 if (!malformed)
847 mid->mid_state = MID_RESPONSE_RECEIVED;
848 else
849 mid->mid_state = MID_RESPONSE_MALFORMED;
850 /*
851 * Trying to handle/dequeue a mid after the send_recv()
852 * function has finished processing it is a bug.
853 */
854 if (mid->mid_flags & MID_DELETED) {
855 spin_unlock(&mid->server->mid_lock);
856 pr_warn_once("trying to dequeue a deleted mid\n");
857 } else {
858 list_del_init(&mid->qhead);
859 mid->mid_flags |= MID_DELETED;
860 spin_unlock(&mid->server->mid_lock);
861 }
862}
863
864static unsigned int
865smb2_get_credits_from_hdr(char *buffer, struct TCP_Server_Info *server)
866{
867 struct smb2_hdr *shdr = (struct smb2_hdr *)buffer;
868
869 /*
870 * SMB1 does not use credits.
871 */
872 if (is_smb1(server))
873 return 0;
874
875 return le16_to_cpu(shdr->CreditRequest);
876}
877
878static void
879handle_mid(struct mid_q_entry *mid, struct TCP_Server_Info *server,
880 char *buf, int malformed)
881{
882 if (server->ops->check_trans2 &&
883 server->ops->check_trans2(mid, server, buf, malformed))
884 return;
885 mid->credits_received = smb2_get_credits_from_hdr(buf, server);
886 mid->resp_buf = buf;
887 mid->large_buf = server->large_buf;
888 /* Was previous buf put in mpx struct for multi-rsp? */
889 if (!mid->multiRsp) {
890 /* smb buffer will be freed by user thread */
891 if (server->large_buf)
892 server->bigbuf = NULL;
893 else
894 server->smallbuf = NULL;
895 }
896 dequeue_mid(mid, malformed);
897}
898
899int
900cifs_enable_signing(struct TCP_Server_Info *server, bool mnt_sign_required)
901{
902 bool srv_sign_required = server->sec_mode & server->vals->signing_required;
903 bool srv_sign_enabled = server->sec_mode & server->vals->signing_enabled;
904 bool mnt_sign_enabled;
905
906 /*
907 * Is signing required by mnt options? If not then check
908 * global_secflags to see if it is there.
909 */
910 if (!mnt_sign_required)
911 mnt_sign_required = ((global_secflags & CIFSSEC_MUST_SIGN) ==
912 CIFSSEC_MUST_SIGN);
913
914 /*
915 * If signing is required then it's automatically enabled too,
916 * otherwise, check to see if the secflags allow it.
917 */
918 mnt_sign_enabled = mnt_sign_required ? mnt_sign_required :
919 (global_secflags & CIFSSEC_MAY_SIGN);
920
921 /* If server requires signing, does client allow it? */
922 if (srv_sign_required) {
923 if (!mnt_sign_enabled) {
924 cifs_dbg(VFS, "Server requires signing, but it's disabled in SecurityFlags!\n");
925 return -EOPNOTSUPP;
926 }
927 server->sign = true;
928 }
929
930 /* If client requires signing, does server allow it? */
931 if (mnt_sign_required) {
932 if (!srv_sign_enabled) {
933 cifs_dbg(VFS, "Server does not support signing!\n");
934 return -EOPNOTSUPP;
935 }
936 server->sign = true;
937 }
938
939 if (cifs_rdma_enabled(server) && server->sign)
940 cifs_dbg(VFS, "Signing is enabled, and RDMA read/write will be disabled\n");
941
942 return 0;
943}
944
945static noinline_for_stack void
946clean_demultiplex_info(struct TCP_Server_Info *server)
947{
948 int length;
949
950 /* take it off the list, if it's not already */
951 spin_lock(&server->srv_lock);
952 list_del_init(&server->tcp_ses_list);
953 spin_unlock(&server->srv_lock);
954
955 cancel_delayed_work_sync(&server->echo);
956
957 spin_lock(&server->srv_lock);
958 server->tcpStatus = CifsExiting;
959 spin_unlock(&server->srv_lock);
960 wake_up_all(&server->response_q);
961
962 /* check if we have blocked requests that need to free */
963 spin_lock(&server->req_lock);
964 if (server->credits <= 0)
965 server->credits = 1;
966 spin_unlock(&server->req_lock);
967 /*
968 * Although there should not be any requests blocked on this queue it
969 * can not hurt to be paranoid and try to wake up requests that may
970 * haven been blocked when more than 50 at time were on the wire to the
971 * same server - they now will see the session is in exit state and get
972 * out of SendReceive.
973 */
974 wake_up_all(&server->request_q);
975 /* give those requests time to exit */
976 msleep(125);
977 if (cifs_rdma_enabled(server))
978 smbd_destroy(server);
979 if (server->ssocket) {
980 sock_release(server->ssocket);
981 server->ssocket = NULL;
982 }
983
984 if (!list_empty(&server->pending_mid_q)) {
985 struct list_head dispose_list;
986 struct mid_q_entry *mid_entry;
987 struct list_head *tmp, *tmp2;
988
989 INIT_LIST_HEAD(&dispose_list);
990 spin_lock(&server->mid_lock);
991 list_for_each_safe(tmp, tmp2, &server->pending_mid_q) {
992 mid_entry = list_entry(tmp, struct mid_q_entry, qhead);
993 cifs_dbg(FYI, "Clearing mid %llu\n", mid_entry->mid);
994 kref_get(&mid_entry->refcount);
995 mid_entry->mid_state = MID_SHUTDOWN;
996 list_move(&mid_entry->qhead, &dispose_list);
997 mid_entry->mid_flags |= MID_DELETED;
998 }
999 spin_unlock(&server->mid_lock);
1000
1001 /* now walk dispose list and issue callbacks */
1002 list_for_each_safe(tmp, tmp2, &dispose_list) {
1003 mid_entry = list_entry(tmp, struct mid_q_entry, qhead);
1004 cifs_dbg(FYI, "Callback mid %llu\n", mid_entry->mid);
1005 list_del_init(&mid_entry->qhead);
1006 mid_entry->callback(mid_entry);
1007 release_mid(mid_entry);
1008 }
1009 /* 1/8th of sec is more than enough time for them to exit */
1010 msleep(125);
1011 }
1012
1013 if (!list_empty(&server->pending_mid_q)) {
1014 /*
1015 * mpx threads have not exited yet give them at least the smb
1016 * send timeout time for long ops.
1017 *
1018 * Due to delays on oplock break requests, we need to wait at
1019 * least 45 seconds before giving up on a request getting a
1020 * response and going ahead and killing cifsd.
1021 */
1022 cifs_dbg(FYI, "Wait for exit from demultiplex thread\n");
1023 msleep(46000);
1024 /*
1025 * If threads still have not exited they are probably never
1026 * coming home not much else we can do but free the memory.
1027 */
1028 }
1029
1030 kfree(server->leaf_fullpath);
1031 kfree(server);
1032
1033 length = atomic_dec_return(&tcpSesAllocCount);
1034 if (length > 0)
1035 mempool_resize(cifs_req_poolp, length + cifs_min_rcv);
1036}
1037
1038static int
1039standard_receive3(struct TCP_Server_Info *server, struct mid_q_entry *mid)
1040{
1041 int length;
1042 char *buf = server->smallbuf;
1043 unsigned int pdu_length = server->pdu_size;
1044
1045 /* make sure this will fit in a large buffer */
1046 if (pdu_length > CIFSMaxBufSize + MAX_HEADER_SIZE(server) -
1047 HEADER_PREAMBLE_SIZE(server)) {
1048 cifs_server_dbg(VFS, "SMB response too long (%u bytes)\n", pdu_length);
1049 cifs_reconnect(server, true);
1050 return -ECONNABORTED;
1051 }
1052
1053 /* switch to large buffer if too big for a small one */
1054 if (pdu_length > MAX_CIFS_SMALL_BUFFER_SIZE - 4) {
1055 server->large_buf = true;
1056 memcpy(server->bigbuf, buf, server->total_read);
1057 buf = server->bigbuf;
1058 }
1059
1060 /* now read the rest */
1061 length = cifs_read_from_socket(server, buf + HEADER_SIZE(server) - 1,
1062 pdu_length - MID_HEADER_SIZE(server));
1063
1064 if (length < 0)
1065 return length;
1066 server->total_read += length;
1067
1068 dump_smb(buf, server->total_read);
1069
1070 return cifs_handle_standard(server, mid);
1071}
1072
1073int
1074cifs_handle_standard(struct TCP_Server_Info *server, struct mid_q_entry *mid)
1075{
1076 char *buf = server->large_buf ? server->bigbuf : server->smallbuf;
1077 int rc;
1078
1079 /*
1080 * We know that we received enough to get to the MID as we
1081 * checked the pdu_length earlier. Now check to see
1082 * if the rest of the header is OK.
1083 *
1084 * 48 bytes is enough to display the header and a little bit
1085 * into the payload for debugging purposes.
1086 */
1087 rc = server->ops->check_message(buf, server->total_read, server);
1088 if (rc)
1089 cifs_dump_mem("Bad SMB: ", buf,
1090 min_t(unsigned int, server->total_read, 48));
1091
1092 if (server->ops->is_session_expired &&
1093 server->ops->is_session_expired(buf)) {
1094 cifs_reconnect(server, true);
1095 return -1;
1096 }
1097
1098 if (server->ops->is_status_pending &&
1099 server->ops->is_status_pending(buf, server))
1100 return -1;
1101
1102 if (!mid)
1103 return rc;
1104
1105 handle_mid(mid, server, buf, rc);
1106 return 0;
1107}
1108
1109static void
1110smb2_add_credits_from_hdr(char *buffer, struct TCP_Server_Info *server)
1111{
1112 struct smb2_hdr *shdr = (struct smb2_hdr *)buffer;
1113 int scredits, in_flight;
1114
1115 /*
1116 * SMB1 does not use credits.
1117 */
1118 if (is_smb1(server))
1119 return;
1120
1121 if (shdr->CreditRequest) {
1122 spin_lock(&server->req_lock);
1123 server->credits += le16_to_cpu(shdr->CreditRequest);
1124 scredits = server->credits;
1125 in_flight = server->in_flight;
1126 spin_unlock(&server->req_lock);
1127 wake_up(&server->request_q);
1128
1129 trace_smb3_hdr_credits(server->CurrentMid,
1130 server->conn_id, server->hostname, scredits,
1131 le16_to_cpu(shdr->CreditRequest), in_flight);
1132 cifs_server_dbg(FYI, "%s: added %u credits total=%d\n",
1133 __func__, le16_to_cpu(shdr->CreditRequest),
1134 scredits);
1135 }
1136}
1137
1138
1139static int
1140cifs_demultiplex_thread(void *p)
1141{
1142 int i, num_mids, length;
1143 struct TCP_Server_Info *server = p;
1144 unsigned int pdu_length;
1145 unsigned int next_offset;
1146 char *buf = NULL;
1147 struct task_struct *task_to_wake = NULL;
1148 struct mid_q_entry *mids[MAX_COMPOUND];
1149 char *bufs[MAX_COMPOUND];
1150 unsigned int noreclaim_flag, num_io_timeout = 0;
1151 bool pending_reconnect = false;
1152
1153 noreclaim_flag = memalloc_noreclaim_save();
1154 cifs_dbg(FYI, "Demultiplex PID: %d\n", task_pid_nr(current));
1155
1156 length = atomic_inc_return(&tcpSesAllocCount);
1157 if (length > 1)
1158 mempool_resize(cifs_req_poolp, length + cifs_min_rcv);
1159
1160 set_freezable();
1161 allow_kernel_signal(SIGKILL);
1162 while (server->tcpStatus != CifsExiting) {
1163 if (try_to_freeze())
1164 continue;
1165
1166 if (!allocate_buffers(server))
1167 continue;
1168
1169 server->large_buf = false;
1170 buf = server->smallbuf;
1171 pdu_length = 4; /* enough to get RFC1001 header */
1172
1173 length = cifs_read_from_socket(server, buf, pdu_length);
1174 if (length < 0)
1175 continue;
1176
1177 if (is_smb1(server))
1178 server->total_read = length;
1179 else
1180 server->total_read = 0;
1181
1182 /*
1183 * The right amount was read from socket - 4 bytes,
1184 * so we can now interpret the length field.
1185 */
1186 pdu_length = get_rfc1002_length(buf);
1187
1188 cifs_dbg(FYI, "RFC1002 header 0x%x\n", pdu_length);
1189 if (!is_smb_response(server, buf[0]))
1190 continue;
1191
1192 pending_reconnect = false;
1193next_pdu:
1194 server->pdu_size = pdu_length;
1195
1196 /* make sure we have enough to get to the MID */
1197 if (server->pdu_size < MID_HEADER_SIZE(server)) {
1198 cifs_server_dbg(VFS, "SMB response too short (%u bytes)\n",
1199 server->pdu_size);
1200 cifs_reconnect(server, true);
1201 continue;
1202 }
1203
1204 /* read down to the MID */
1205 length = cifs_read_from_socket(server,
1206 buf + HEADER_PREAMBLE_SIZE(server),
1207 MID_HEADER_SIZE(server));
1208 if (length < 0)
1209 continue;
1210 server->total_read += length;
1211
1212 if (server->ops->next_header) {
1213 if (server->ops->next_header(server, buf, &next_offset)) {
1214 cifs_dbg(VFS, "%s: malformed response (next_offset=%u)\n",
1215 __func__, next_offset);
1216 cifs_reconnect(server, true);
1217 continue;
1218 }
1219 if (next_offset)
1220 server->pdu_size = next_offset;
1221 }
1222
1223 memset(mids, 0, sizeof(mids));
1224 memset(bufs, 0, sizeof(bufs));
1225 num_mids = 0;
1226
1227 if (server->ops->is_transform_hdr &&
1228 server->ops->receive_transform &&
1229 server->ops->is_transform_hdr(buf)) {
1230 length = server->ops->receive_transform(server,
1231 mids,
1232 bufs,
1233 &num_mids);
1234 } else {
1235 mids[0] = server->ops->find_mid(server, buf);
1236 bufs[0] = buf;
1237 num_mids = 1;
1238
1239 if (!mids[0] || !mids[0]->receive)
1240 length = standard_receive3(server, mids[0]);
1241 else
1242 length = mids[0]->receive(server, mids[0]);
1243 }
1244
1245 if (length < 0) {
1246 for (i = 0; i < num_mids; i++)
1247 if (mids[i])
1248 release_mid(mids[i]);
1249 continue;
1250 }
1251
1252 if (server->ops->is_status_io_timeout &&
1253 server->ops->is_status_io_timeout(buf)) {
1254 num_io_timeout++;
1255 if (num_io_timeout > MAX_STATUS_IO_TIMEOUT) {
1256 cifs_server_dbg(VFS,
1257 "Number of request timeouts exceeded %d. Reconnecting",
1258 MAX_STATUS_IO_TIMEOUT);
1259
1260 pending_reconnect = true;
1261 num_io_timeout = 0;
1262 }
1263 }
1264
1265 server->lstrp = jiffies;
1266
1267 for (i = 0; i < num_mids; i++) {
1268 if (mids[i] != NULL) {
1269 mids[i]->resp_buf_size = server->pdu_size;
1270
1271 if (bufs[i] != NULL) {
1272 if (server->ops->is_network_name_deleted &&
1273 server->ops->is_network_name_deleted(bufs[i],
1274 server)) {
1275 cifs_server_dbg(FYI,
1276 "Share deleted. Reconnect needed");
1277 }
1278 }
1279
1280 if (!mids[i]->multiRsp || mids[i]->multiEnd)
1281 mids[i]->callback(mids[i]);
1282
1283 release_mid(mids[i]);
1284 } else if (server->ops->is_oplock_break &&
1285 server->ops->is_oplock_break(bufs[i],
1286 server)) {
1287 smb2_add_credits_from_hdr(bufs[i], server);
1288 cifs_dbg(FYI, "Received oplock break\n");
1289 } else {
1290 cifs_server_dbg(VFS, "No task to wake, unknown frame received! NumMids %d\n",
1291 atomic_read(&mid_count));
1292 cifs_dump_mem("Received Data is: ", bufs[i],
1293 HEADER_SIZE(server));
1294 smb2_add_credits_from_hdr(bufs[i], server);
1295#ifdef CONFIG_CIFS_DEBUG2
1296 if (server->ops->dump_detail)
1297 server->ops->dump_detail(bufs[i],
1298 server);
1299 cifs_dump_mids(server);
1300#endif /* CIFS_DEBUG2 */
1301 }
1302 }
1303
1304 if (pdu_length > server->pdu_size) {
1305 if (!allocate_buffers(server))
1306 continue;
1307 pdu_length -= server->pdu_size;
1308 server->total_read = 0;
1309 server->large_buf = false;
1310 buf = server->smallbuf;
1311 goto next_pdu;
1312 }
1313
1314 /* do this reconnect at the very end after processing all MIDs */
1315 if (pending_reconnect)
1316 cifs_reconnect(server, true);
1317
1318 } /* end while !EXITING */
1319
1320 /* buffer usually freed in free_mid - need to free it here on exit */
1321 cifs_buf_release(server->bigbuf);
1322 if (server->smallbuf) /* no sense logging a debug message if NULL */
1323 cifs_small_buf_release(server->smallbuf);
1324
1325 task_to_wake = xchg(&server->tsk, NULL);
1326 clean_demultiplex_info(server);
1327
1328 /* if server->tsk was NULL then wait for a signal before exiting */
1329 if (!task_to_wake) {
1330 set_current_state(TASK_INTERRUPTIBLE);
1331 while (!signal_pending(current)) {
1332 schedule();
1333 set_current_state(TASK_INTERRUPTIBLE);
1334 }
1335 set_current_state(TASK_RUNNING);
1336 }
1337
1338 memalloc_noreclaim_restore(noreclaim_flag);
1339 module_put_and_kthread_exit(0);
1340}
1341
1342int
1343cifs_ipaddr_cmp(struct sockaddr *srcaddr, struct sockaddr *rhs)
1344{
1345 struct sockaddr_in *saddr4 = (struct sockaddr_in *)srcaddr;
1346 struct sockaddr_in *vaddr4 = (struct sockaddr_in *)rhs;
1347 struct sockaddr_in6 *saddr6 = (struct sockaddr_in6 *)srcaddr;
1348 struct sockaddr_in6 *vaddr6 = (struct sockaddr_in6 *)rhs;
1349
1350 switch (srcaddr->sa_family) {
1351 case AF_UNSPEC:
1352 switch (rhs->sa_family) {
1353 case AF_UNSPEC:
1354 return 0;
1355 case AF_INET:
1356 case AF_INET6:
1357 return 1;
1358 default:
1359 return -1;
1360 }
1361 case AF_INET: {
1362 switch (rhs->sa_family) {
1363 case AF_UNSPEC:
1364 return -1;
1365 case AF_INET:
1366 return memcmp(saddr4, vaddr4,
1367 sizeof(struct sockaddr_in));
1368 case AF_INET6:
1369 return 1;
1370 default:
1371 return -1;
1372 }
1373 }
1374 case AF_INET6: {
1375 switch (rhs->sa_family) {
1376 case AF_UNSPEC:
1377 case AF_INET:
1378 return -1;
1379 case AF_INET6:
1380 return memcmp(saddr6,
1381 vaddr6,
1382 sizeof(struct sockaddr_in6));
1383 default:
1384 return -1;
1385 }
1386 }
1387 default:
1388 return -1; /* don't expect to be here */
1389 }
1390}
1391
1392/*
1393 * Returns true if srcaddr isn't specified and rhs isn't specified, or
1394 * if srcaddr is specified and matches the IP address of the rhs argument
1395 */
1396bool
1397cifs_match_ipaddr(struct sockaddr *srcaddr, struct sockaddr *rhs)
1398{
1399 switch (srcaddr->sa_family) {
1400 case AF_UNSPEC:
1401 return (rhs->sa_family == AF_UNSPEC);
1402 case AF_INET: {
1403 struct sockaddr_in *saddr4 = (struct sockaddr_in *)srcaddr;
1404 struct sockaddr_in *vaddr4 = (struct sockaddr_in *)rhs;
1405
1406 return (saddr4->sin_addr.s_addr == vaddr4->sin_addr.s_addr);
1407 }
1408 case AF_INET6: {
1409 struct sockaddr_in6 *saddr6 = (struct sockaddr_in6 *)srcaddr;
1410 struct sockaddr_in6 *vaddr6 = (struct sockaddr_in6 *)rhs;
1411
1412 return (ipv6_addr_equal(&saddr6->sin6_addr, &vaddr6->sin6_addr)
1413 && saddr6->sin6_scope_id == vaddr6->sin6_scope_id);
1414 }
1415 default:
1416 WARN_ON(1);
1417 return false; /* don't expect to be here */
1418 }
1419}
1420
1421/*
1422 * If no port is specified in addr structure, we try to match with 445 port
1423 * and if it fails - with 139 ports. It should be called only if address
1424 * families of server and addr are equal.
1425 */
1426static bool
1427match_port(struct TCP_Server_Info *server, struct sockaddr *addr)
1428{
1429 __be16 port, *sport;
1430
1431 /* SMBDirect manages its own ports, don't match it here */
1432 if (server->rdma)
1433 return true;
1434
1435 switch (addr->sa_family) {
1436 case AF_INET:
1437 sport = &((struct sockaddr_in *) &server->dstaddr)->sin_port;
1438 port = ((struct sockaddr_in *) addr)->sin_port;
1439 break;
1440 case AF_INET6:
1441 sport = &((struct sockaddr_in6 *) &server->dstaddr)->sin6_port;
1442 port = ((struct sockaddr_in6 *) addr)->sin6_port;
1443 break;
1444 default:
1445 WARN_ON(1);
1446 return false;
1447 }
1448
1449 if (!port) {
1450 port = htons(CIFS_PORT);
1451 if (port == *sport)
1452 return true;
1453
1454 port = htons(RFC1001_PORT);
1455 }
1456
1457 return port == *sport;
1458}
1459
1460static bool match_server_address(struct TCP_Server_Info *server, struct sockaddr *addr)
1461{
1462 if (!cifs_match_ipaddr(addr, (struct sockaddr *)&server->dstaddr))
1463 return false;
1464
1465 return true;
1466}
1467
1468static bool
1469match_security(struct TCP_Server_Info *server, struct smb3_fs_context *ctx)
1470{
1471 /*
1472 * The select_sectype function should either return the ctx->sectype
1473 * that was specified, or "Unspecified" if that sectype was not
1474 * compatible with the given NEGOTIATE request.
1475 */
1476 if (server->ops->select_sectype(server, ctx->sectype)
1477 == Unspecified)
1478 return false;
1479
1480 /*
1481 * Now check if signing mode is acceptable. No need to check
1482 * global_secflags at this point since if MUST_SIGN is set then
1483 * the server->sign had better be too.
1484 */
1485 if (ctx->sign && !server->sign)
1486 return false;
1487
1488 return true;
1489}
1490
1491/* this function must be called with srv_lock held */
1492static int match_server(struct TCP_Server_Info *server,
1493 struct smb3_fs_context *ctx,
1494 bool match_super)
1495{
1496 struct sockaddr *addr = (struct sockaddr *)&ctx->dstaddr;
1497
1498 lockdep_assert_held(&server->srv_lock);
1499
1500 if (ctx->nosharesock)
1501 return 0;
1502
1503 /* this server does not share socket */
1504 if (server->nosharesock)
1505 return 0;
1506
1507 /* If multidialect negotiation see if existing sessions match one */
1508 if (strcmp(ctx->vals->version_string, SMB3ANY_VERSION_STRING) == 0) {
1509 if (server->vals->protocol_id < SMB30_PROT_ID)
1510 return 0;
1511 } else if (strcmp(ctx->vals->version_string,
1512 SMBDEFAULT_VERSION_STRING) == 0) {
1513 if (server->vals->protocol_id < SMB21_PROT_ID)
1514 return 0;
1515 } else if ((server->vals != ctx->vals) || (server->ops != ctx->ops))
1516 return 0;
1517
1518 if (!net_eq(cifs_net_ns(server), current->nsproxy->net_ns))
1519 return 0;
1520
1521 if (!cifs_match_ipaddr((struct sockaddr *)&ctx->srcaddr,
1522 (struct sockaddr *)&server->srcaddr))
1523 return 0;
1524 /*
1525 * When matching cifs.ko superblocks (@match_super == true), we can't
1526 * really match either @server->leaf_fullpath or @server->dstaddr
1527 * directly since this @server might belong to a completely different
1528 * server -- in case of domain-based DFS referrals or DFS links -- as
1529 * provided earlier by mount(2) through 'source' and 'ip' options.
1530 *
1531 * Otherwise, match the DFS referral in @server->leaf_fullpath or the
1532 * destination address in @server->dstaddr.
1533 *
1534 * When using 'nodfs' mount option, we avoid sharing it with DFS
1535 * connections as they might failover.
1536 */
1537 if (!match_super) {
1538 if (!ctx->nodfs) {
1539 if (server->leaf_fullpath) {
1540 if (!ctx->leaf_fullpath ||
1541 strcasecmp(server->leaf_fullpath,
1542 ctx->leaf_fullpath))
1543 return 0;
1544 } else if (ctx->leaf_fullpath) {
1545 return 0;
1546 }
1547 } else if (server->leaf_fullpath) {
1548 return 0;
1549 }
1550 }
1551
1552 /*
1553 * Match for a regular connection (address/hostname/port) which has no
1554 * DFS referrals set.
1555 */
1556 if (!server->leaf_fullpath &&
1557 (strcasecmp(server->hostname, ctx->server_hostname) ||
1558 !match_server_address(server, addr) ||
1559 !match_port(server, addr)))
1560 return 0;
1561
1562 if (!match_security(server, ctx))
1563 return 0;
1564
1565 if (server->echo_interval != ctx->echo_interval * HZ)
1566 return 0;
1567
1568 if (server->rdma != ctx->rdma)
1569 return 0;
1570
1571 if (server->ignore_signature != ctx->ignore_signature)
1572 return 0;
1573
1574 if (server->min_offload != ctx->min_offload)
1575 return 0;
1576
1577 if (server->retrans != ctx->retrans)
1578 return 0;
1579
1580 return 1;
1581}
1582
1583struct TCP_Server_Info *
1584cifs_find_tcp_session(struct smb3_fs_context *ctx)
1585{
1586 struct TCP_Server_Info *server;
1587
1588 spin_lock(&cifs_tcp_ses_lock);
1589 list_for_each_entry(server, &cifs_tcp_ses_list, tcp_ses_list) {
1590 spin_lock(&server->srv_lock);
1591 /*
1592 * Skip ses channels since they're only handled in lower layers
1593 * (e.g. cifs_send_recv).
1594 */
1595 if (SERVER_IS_CHAN(server) ||
1596 !match_server(server, ctx, false)) {
1597 spin_unlock(&server->srv_lock);
1598 continue;
1599 }
1600 spin_unlock(&server->srv_lock);
1601
1602 ++server->srv_count;
1603 spin_unlock(&cifs_tcp_ses_lock);
1604 cifs_dbg(FYI, "Existing tcp session with server found\n");
1605 return server;
1606 }
1607 spin_unlock(&cifs_tcp_ses_lock);
1608 return NULL;
1609}
1610
1611void
1612cifs_put_tcp_session(struct TCP_Server_Info *server, int from_reconnect)
1613{
1614 struct task_struct *task;
1615
1616 spin_lock(&cifs_tcp_ses_lock);
1617 if (--server->srv_count > 0) {
1618 spin_unlock(&cifs_tcp_ses_lock);
1619 return;
1620 }
1621
1622 /* srv_count can never go negative */
1623 WARN_ON(server->srv_count < 0);
1624
1625 put_net(cifs_net_ns(server));
1626
1627 list_del_init(&server->tcp_ses_list);
1628 spin_unlock(&cifs_tcp_ses_lock);
1629
1630 cancel_delayed_work_sync(&server->echo);
1631
1632 if (from_reconnect)
1633 /*
1634 * Avoid deadlock here: reconnect work calls
1635 * cifs_put_tcp_session() at its end. Need to be sure
1636 * that reconnect work does nothing with server pointer after
1637 * that step.
1638 */
1639 cancel_delayed_work(&server->reconnect);
1640 else
1641 cancel_delayed_work_sync(&server->reconnect);
1642
1643 /* For secondary channels, we pick up ref-count on the primary server */
1644 if (SERVER_IS_CHAN(server))
1645 cifs_put_tcp_session(server->primary_server, from_reconnect);
1646
1647 spin_lock(&server->srv_lock);
1648 server->tcpStatus = CifsExiting;
1649 spin_unlock(&server->srv_lock);
1650
1651 cifs_crypto_secmech_release(server);
1652
1653 kfree_sensitive(server->session_key.response);
1654 server->session_key.response = NULL;
1655 server->session_key.len = 0;
1656 kfree(server->hostname);
1657 server->hostname = NULL;
1658
1659 task = xchg(&server->tsk, NULL);
1660 if (task)
1661 send_sig(SIGKILL, task, 1);
1662}
1663
1664struct TCP_Server_Info *
1665cifs_get_tcp_session(struct smb3_fs_context *ctx,
1666 struct TCP_Server_Info *primary_server)
1667{
1668 struct TCP_Server_Info *tcp_ses = NULL;
1669 int rc;
1670
1671 cifs_dbg(FYI, "UNC: %s\n", ctx->UNC);
1672
1673 /* see if we already have a matching tcp_ses */
1674 tcp_ses = cifs_find_tcp_session(ctx);
1675 if (tcp_ses)
1676 return tcp_ses;
1677
1678 tcp_ses = kzalloc(sizeof(struct TCP_Server_Info), GFP_KERNEL);
1679 if (!tcp_ses) {
1680 rc = -ENOMEM;
1681 goto out_err;
1682 }
1683
1684 tcp_ses->hostname = kstrdup(ctx->server_hostname, GFP_KERNEL);
1685 if (!tcp_ses->hostname) {
1686 rc = -ENOMEM;
1687 goto out_err;
1688 }
1689
1690 if (ctx->leaf_fullpath) {
1691 tcp_ses->leaf_fullpath = kstrdup(ctx->leaf_fullpath, GFP_KERNEL);
1692 if (!tcp_ses->leaf_fullpath) {
1693 rc = -ENOMEM;
1694 goto out_err;
1695 }
1696 }
1697
1698 if (ctx->nosharesock)
1699 tcp_ses->nosharesock = true;
1700
1701 tcp_ses->ops = ctx->ops;
1702 tcp_ses->vals = ctx->vals;
1703 cifs_set_net_ns(tcp_ses, get_net(current->nsproxy->net_ns));
1704
1705 tcp_ses->conn_id = atomic_inc_return(&tcpSesNextId);
1706 tcp_ses->noblockcnt = ctx->rootfs;
1707 tcp_ses->noblocksnd = ctx->noblocksnd || ctx->rootfs;
1708 tcp_ses->noautotune = ctx->noautotune;
1709 tcp_ses->tcp_nodelay = ctx->sockopt_tcp_nodelay;
1710 tcp_ses->rdma = ctx->rdma;
1711 tcp_ses->in_flight = 0;
1712 tcp_ses->max_in_flight = 0;
1713 tcp_ses->credits = 1;
1714 if (primary_server) {
1715 spin_lock(&cifs_tcp_ses_lock);
1716 ++primary_server->srv_count;
1717 spin_unlock(&cifs_tcp_ses_lock);
1718 tcp_ses->primary_server = primary_server;
1719 }
1720 init_waitqueue_head(&tcp_ses->response_q);
1721 init_waitqueue_head(&tcp_ses->request_q);
1722 INIT_LIST_HEAD(&tcp_ses->pending_mid_q);
1723 mutex_init(&tcp_ses->_srv_mutex);
1724 memcpy(tcp_ses->workstation_RFC1001_name,
1725 ctx->source_rfc1001_name, RFC1001_NAME_LEN_WITH_NULL);
1726 memcpy(tcp_ses->server_RFC1001_name,
1727 ctx->target_rfc1001_name, RFC1001_NAME_LEN_WITH_NULL);
1728 tcp_ses->session_estab = false;
1729 tcp_ses->sequence_number = 0;
1730 tcp_ses->channel_sequence_num = 0; /* only tracked for primary channel */
1731 tcp_ses->reconnect_instance = 1;
1732 tcp_ses->lstrp = jiffies;
1733 tcp_ses->compress_algorithm = cpu_to_le16(ctx->compression);
1734 spin_lock_init(&tcp_ses->req_lock);
1735 spin_lock_init(&tcp_ses->srv_lock);
1736 spin_lock_init(&tcp_ses->mid_lock);
1737 INIT_LIST_HEAD(&tcp_ses->tcp_ses_list);
1738 INIT_LIST_HEAD(&tcp_ses->smb_ses_list);
1739 INIT_DELAYED_WORK(&tcp_ses->echo, cifs_echo_request);
1740 INIT_DELAYED_WORK(&tcp_ses->reconnect, smb2_reconnect_server);
1741 mutex_init(&tcp_ses->reconnect_mutex);
1742#ifdef CONFIG_CIFS_DFS_UPCALL
1743 mutex_init(&tcp_ses->refpath_lock);
1744#endif
1745 memcpy(&tcp_ses->srcaddr, &ctx->srcaddr,
1746 sizeof(tcp_ses->srcaddr));
1747 memcpy(&tcp_ses->dstaddr, &ctx->dstaddr,
1748 sizeof(tcp_ses->dstaddr));
1749 if (ctx->use_client_guid)
1750 memcpy(tcp_ses->client_guid, ctx->client_guid,
1751 SMB2_CLIENT_GUID_SIZE);
1752 else
1753 generate_random_uuid(tcp_ses->client_guid);
1754 /*
1755 * at this point we are the only ones with the pointer
1756 * to the struct since the kernel thread not created yet
1757 * no need to spinlock this init of tcpStatus or srv_count
1758 */
1759 tcp_ses->tcpStatus = CifsNew;
1760 ++tcp_ses->srv_count;
1761
1762 if (ctx->echo_interval >= SMB_ECHO_INTERVAL_MIN &&
1763 ctx->echo_interval <= SMB_ECHO_INTERVAL_MAX)
1764 tcp_ses->echo_interval = ctx->echo_interval * HZ;
1765 else
1766 tcp_ses->echo_interval = SMB_ECHO_INTERVAL_DEFAULT * HZ;
1767 if (tcp_ses->rdma) {
1768#ifndef CONFIG_CIFS_SMB_DIRECT
1769 cifs_dbg(VFS, "CONFIG_CIFS_SMB_DIRECT is not enabled\n");
1770 rc = -ENOENT;
1771 goto out_err_crypto_release;
1772#endif
1773 tcp_ses->smbd_conn = smbd_get_connection(
1774 tcp_ses, (struct sockaddr *)&ctx->dstaddr);
1775 if (tcp_ses->smbd_conn) {
1776 cifs_dbg(VFS, "RDMA transport established\n");
1777 rc = 0;
1778 goto smbd_connected;
1779 } else {
1780 rc = -ENOENT;
1781 goto out_err_crypto_release;
1782 }
1783 }
1784 rc = ip_connect(tcp_ses);
1785 if (rc < 0) {
1786 cifs_dbg(VFS, "Error connecting to socket. Aborting operation.\n");
1787 goto out_err_crypto_release;
1788 }
1789smbd_connected:
1790 /*
1791 * since we're in a cifs function already, we know that
1792 * this will succeed. No need for try_module_get().
1793 */
1794 __module_get(THIS_MODULE);
1795 tcp_ses->tsk = kthread_run(cifs_demultiplex_thread,
1796 tcp_ses, "cifsd");
1797 if (IS_ERR(tcp_ses->tsk)) {
1798 rc = PTR_ERR(tcp_ses->tsk);
1799 cifs_dbg(VFS, "error %d create cifsd thread\n", rc);
1800 module_put(THIS_MODULE);
1801 goto out_err_crypto_release;
1802 }
1803 tcp_ses->min_offload = ctx->min_offload;
1804 tcp_ses->retrans = ctx->retrans;
1805 /*
1806 * at this point we are the only ones with the pointer
1807 * to the struct since the kernel thread not created yet
1808 * no need to spinlock this update of tcpStatus
1809 */
1810 spin_lock(&tcp_ses->srv_lock);
1811 tcp_ses->tcpStatus = CifsNeedNegotiate;
1812 spin_unlock(&tcp_ses->srv_lock);
1813
1814 if ((ctx->max_credits < 20) || (ctx->max_credits > 60000))
1815 tcp_ses->max_credits = SMB2_MAX_CREDITS_AVAILABLE;
1816 else
1817 tcp_ses->max_credits = ctx->max_credits;
1818
1819 tcp_ses->nr_targets = 1;
1820 tcp_ses->ignore_signature = ctx->ignore_signature;
1821 /* thread spawned, put it on the list */
1822 spin_lock(&cifs_tcp_ses_lock);
1823 list_add(&tcp_ses->tcp_ses_list, &cifs_tcp_ses_list);
1824 spin_unlock(&cifs_tcp_ses_lock);
1825
1826 /* queue echo request delayed work */
1827 queue_delayed_work(cifsiod_wq, &tcp_ses->echo, tcp_ses->echo_interval);
1828
1829 return tcp_ses;
1830
1831out_err_crypto_release:
1832 cifs_crypto_secmech_release(tcp_ses);
1833
1834 put_net(cifs_net_ns(tcp_ses));
1835
1836out_err:
1837 if (tcp_ses) {
1838 if (SERVER_IS_CHAN(tcp_ses))
1839 cifs_put_tcp_session(tcp_ses->primary_server, false);
1840 kfree(tcp_ses->hostname);
1841 kfree(tcp_ses->leaf_fullpath);
1842 if (tcp_ses->ssocket)
1843 sock_release(tcp_ses->ssocket);
1844 kfree(tcp_ses);
1845 }
1846 return ERR_PTR(rc);
1847}
1848
1849/* this function must be called with ses_lock and chan_lock held */
1850static int match_session(struct cifs_ses *ses, struct smb3_fs_context *ctx)
1851{
1852 if (ctx->sectype != Unspecified &&
1853 ctx->sectype != ses->sectype)
1854 return 0;
1855
1856 /*
1857 * If an existing session is limited to less channels than
1858 * requested, it should not be reused
1859 */
1860 if (ses->chan_max < ctx->max_channels)
1861 return 0;
1862
1863 switch (ses->sectype) {
1864 case Kerberos:
1865 if (!uid_eq(ctx->cred_uid, ses->cred_uid))
1866 return 0;
1867 break;
1868 default:
1869 /* NULL username means anonymous session */
1870 if (ses->user_name == NULL) {
1871 if (!ctx->nullauth)
1872 return 0;
1873 break;
1874 }
1875
1876 /* anything else takes username/password */
1877 if (strncmp(ses->user_name,
1878 ctx->username ? ctx->username : "",
1879 CIFS_MAX_USERNAME_LEN))
1880 return 0;
1881 if ((ctx->username && strlen(ctx->username) != 0) &&
1882 ses->password != NULL &&
1883 strncmp(ses->password,
1884 ctx->password ? ctx->password : "",
1885 CIFS_MAX_PASSWORD_LEN))
1886 return 0;
1887 }
1888
1889 if (strcmp(ctx->local_nls->charset, ses->local_nls->charset))
1890 return 0;
1891
1892 return 1;
1893}
1894
1895/**
1896 * cifs_setup_ipc - helper to setup the IPC tcon for the session
1897 * @ses: smb session to issue the request on
1898 * @ctx: the superblock configuration context to use for building the
1899 * new tree connection for the IPC (interprocess communication RPC)
1900 *
1901 * A new IPC connection is made and stored in the session
1902 * tcon_ipc. The IPC tcon has the same lifetime as the session.
1903 */
1904static int
1905cifs_setup_ipc(struct cifs_ses *ses, struct smb3_fs_context *ctx)
1906{
1907 int rc = 0, xid;
1908 struct cifs_tcon *tcon;
1909 char unc[SERVER_NAME_LENGTH + sizeof("//x/IPC$")] = {0};
1910 bool seal = false;
1911 struct TCP_Server_Info *server = ses->server;
1912
1913 /*
1914 * If the mount request that resulted in the creation of the
1915 * session requires encryption, force IPC to be encrypted too.
1916 */
1917 if (ctx->seal) {
1918 if (server->capabilities & SMB2_GLOBAL_CAP_ENCRYPTION)
1919 seal = true;
1920 else {
1921 cifs_server_dbg(VFS,
1922 "IPC: server doesn't support encryption\n");
1923 return -EOPNOTSUPP;
1924 }
1925 }
1926
1927 /* no need to setup directory caching on IPC share, so pass in false */
1928 tcon = tcon_info_alloc(false);
1929 if (tcon == NULL)
1930 return -ENOMEM;
1931
1932 spin_lock(&server->srv_lock);
1933 scnprintf(unc, sizeof(unc), "\\\\%s\\IPC$", server->hostname);
1934 spin_unlock(&server->srv_lock);
1935
1936 xid = get_xid();
1937 tcon->ses = ses;
1938 tcon->ipc = true;
1939 tcon->seal = seal;
1940 rc = server->ops->tree_connect(xid, ses, unc, tcon, ctx->local_nls);
1941 free_xid(xid);
1942
1943 if (rc) {
1944 cifs_server_dbg(VFS, "failed to connect to IPC (rc=%d)\n", rc);
1945 tconInfoFree(tcon);
1946 goto out;
1947 }
1948
1949 cifs_dbg(FYI, "IPC tcon rc=%d ipc tid=0x%x\n", rc, tcon->tid);
1950
1951 spin_lock(&tcon->tc_lock);
1952 tcon->status = TID_GOOD;
1953 spin_unlock(&tcon->tc_lock);
1954 ses->tcon_ipc = tcon;
1955out:
1956 return rc;
1957}
1958
1959/**
1960 * cifs_free_ipc - helper to release the session IPC tcon
1961 * @ses: smb session to unmount the IPC from
1962 *
1963 * Needs to be called everytime a session is destroyed.
1964 *
1965 * On session close, the IPC is closed and the server must release all tcons of the session.
1966 * No need to send a tree disconnect here.
1967 *
1968 * Besides, it will make the server to not close durable and resilient files on session close, as
1969 * specified in MS-SMB2 3.3.5.6 Receiving an SMB2 LOGOFF Request.
1970 */
1971static int
1972cifs_free_ipc(struct cifs_ses *ses)
1973{
1974 struct cifs_tcon *tcon = ses->tcon_ipc;
1975
1976 if (tcon == NULL)
1977 return 0;
1978
1979 tconInfoFree(tcon);
1980 ses->tcon_ipc = NULL;
1981 return 0;
1982}
1983
1984static struct cifs_ses *
1985cifs_find_smb_ses(struct TCP_Server_Info *server, struct smb3_fs_context *ctx)
1986{
1987 struct cifs_ses *ses, *ret = NULL;
1988
1989 spin_lock(&cifs_tcp_ses_lock);
1990 list_for_each_entry(ses, &server->smb_ses_list, smb_ses_list) {
1991 spin_lock(&ses->ses_lock);
1992 if (ses->ses_status == SES_EXITING) {
1993 spin_unlock(&ses->ses_lock);
1994 continue;
1995 }
1996 spin_lock(&ses->chan_lock);
1997 if (match_session(ses, ctx)) {
1998 spin_unlock(&ses->chan_lock);
1999 spin_unlock(&ses->ses_lock);
2000 ret = ses;
2001 break;
2002 }
2003 spin_unlock(&ses->chan_lock);
2004 spin_unlock(&ses->ses_lock);
2005 }
2006 if (ret)
2007 cifs_smb_ses_inc_refcount(ret);
2008 spin_unlock(&cifs_tcp_ses_lock);
2009 return ret;
2010}
2011
2012void __cifs_put_smb_ses(struct cifs_ses *ses)
2013{
2014 struct TCP_Server_Info *server = ses->server;
2015 unsigned int xid;
2016 size_t i;
2017 int rc;
2018
2019 spin_lock(&ses->ses_lock);
2020 if (ses->ses_status == SES_EXITING) {
2021 spin_unlock(&ses->ses_lock);
2022 return;
2023 }
2024 spin_unlock(&ses->ses_lock);
2025
2026 cifs_dbg(FYI, "%s: ses_count=%d\n", __func__, ses->ses_count);
2027 cifs_dbg(FYI,
2028 "%s: ses ipc: %s\n", __func__, ses->tcon_ipc ? ses->tcon_ipc->tree_name : "NONE");
2029
2030 spin_lock(&cifs_tcp_ses_lock);
2031 if (--ses->ses_count > 0) {
2032 spin_unlock(&cifs_tcp_ses_lock);
2033 return;
2034 }
2035 spin_lock(&ses->ses_lock);
2036 if (ses->ses_status == SES_GOOD)
2037 ses->ses_status = SES_EXITING;
2038 spin_unlock(&ses->ses_lock);
2039 spin_unlock(&cifs_tcp_ses_lock);
2040
2041 /* ses_count can never go negative */
2042 WARN_ON(ses->ses_count < 0);
2043
2044 spin_lock(&ses->ses_lock);
2045 if (ses->ses_status == SES_EXITING && server->ops->logoff) {
2046 spin_unlock(&ses->ses_lock);
2047 cifs_free_ipc(ses);
2048 xid = get_xid();
2049 rc = server->ops->logoff(xid, ses);
2050 if (rc)
2051 cifs_server_dbg(VFS, "%s: Session Logoff failure rc=%d\n",
2052 __func__, rc);
2053 _free_xid(xid);
2054 } else {
2055 spin_unlock(&ses->ses_lock);
2056 cifs_free_ipc(ses);
2057 }
2058
2059 spin_lock(&cifs_tcp_ses_lock);
2060 list_del_init(&ses->smb_ses_list);
2061 spin_unlock(&cifs_tcp_ses_lock);
2062
2063 /* close any extra channels */
2064 for (i = 1; i < ses->chan_count; i++) {
2065 if (ses->chans[i].iface) {
2066 kref_put(&ses->chans[i].iface->refcount, release_iface);
2067 ses->chans[i].iface = NULL;
2068 }
2069 cifs_put_tcp_session(ses->chans[i].server, 0);
2070 ses->chans[i].server = NULL;
2071 }
2072
2073 /* we now account for primary channel in iface->refcount */
2074 if (ses->chans[0].iface) {
2075 kref_put(&ses->chans[0].iface->refcount, release_iface);
2076 ses->chans[0].server = NULL;
2077 }
2078
2079 sesInfoFree(ses);
2080 cifs_put_tcp_session(server, 0);
2081}
2082
2083#ifdef CONFIG_KEYS
2084
2085/* strlen("cifs:a:") + CIFS_MAX_DOMAINNAME_LEN + 1 */
2086#define CIFSCREDS_DESC_SIZE (7 + CIFS_MAX_DOMAINNAME_LEN + 1)
2087
2088/* Populate username and pw fields from keyring if possible */
2089static int
2090cifs_set_cifscreds(struct smb3_fs_context *ctx, struct cifs_ses *ses)
2091{
2092 int rc = 0;
2093 int is_domain = 0;
2094 const char *delim, *payload;
2095 char *desc;
2096 ssize_t len;
2097 struct key *key;
2098 struct TCP_Server_Info *server = ses->server;
2099 struct sockaddr_in *sa;
2100 struct sockaddr_in6 *sa6;
2101 const struct user_key_payload *upayload;
2102
2103 desc = kmalloc(CIFSCREDS_DESC_SIZE, GFP_KERNEL);
2104 if (!desc)
2105 return -ENOMEM;
2106
2107 /* try to find an address key first */
2108 switch (server->dstaddr.ss_family) {
2109 case AF_INET:
2110 sa = (struct sockaddr_in *)&server->dstaddr;
2111 sprintf(desc, "cifs:a:%pI4", &sa->sin_addr.s_addr);
2112 break;
2113 case AF_INET6:
2114 sa6 = (struct sockaddr_in6 *)&server->dstaddr;
2115 sprintf(desc, "cifs:a:%pI6c", &sa6->sin6_addr.s6_addr);
2116 break;
2117 default:
2118 cifs_dbg(FYI, "Bad ss_family (%hu)\n",
2119 server->dstaddr.ss_family);
2120 rc = -EINVAL;
2121 goto out_err;
2122 }
2123
2124 cifs_dbg(FYI, "%s: desc=%s\n", __func__, desc);
2125 key = request_key(&key_type_logon, desc, "");
2126 if (IS_ERR(key)) {
2127 if (!ses->domainName) {
2128 cifs_dbg(FYI, "domainName is NULL\n");
2129 rc = PTR_ERR(key);
2130 goto out_err;
2131 }
2132
2133 /* didn't work, try to find a domain key */
2134 sprintf(desc, "cifs:d:%s", ses->domainName);
2135 cifs_dbg(FYI, "%s: desc=%s\n", __func__, desc);
2136 key = request_key(&key_type_logon, desc, "");
2137 if (IS_ERR(key)) {
2138 rc = PTR_ERR(key);
2139 goto out_err;
2140 }
2141 is_domain = 1;
2142 }
2143
2144 down_read(&key->sem);
2145 upayload = user_key_payload_locked(key);
2146 if (IS_ERR_OR_NULL(upayload)) {
2147 rc = upayload ? PTR_ERR(upayload) : -EINVAL;
2148 goto out_key_put;
2149 }
2150
2151 /* find first : in payload */
2152 payload = upayload->data;
2153 delim = strnchr(payload, upayload->datalen, ':');
2154 cifs_dbg(FYI, "payload=%s\n", payload);
2155 if (!delim) {
2156 cifs_dbg(FYI, "Unable to find ':' in payload (datalen=%d)\n",
2157 upayload->datalen);
2158 rc = -EINVAL;
2159 goto out_key_put;
2160 }
2161
2162 len = delim - payload;
2163 if (len > CIFS_MAX_USERNAME_LEN || len <= 0) {
2164 cifs_dbg(FYI, "Bad value from username search (len=%zd)\n",
2165 len);
2166 rc = -EINVAL;
2167 goto out_key_put;
2168 }
2169
2170 ctx->username = kstrndup(payload, len, GFP_KERNEL);
2171 if (!ctx->username) {
2172 cifs_dbg(FYI, "Unable to allocate %zd bytes for username\n",
2173 len);
2174 rc = -ENOMEM;
2175 goto out_key_put;
2176 }
2177 cifs_dbg(FYI, "%s: username=%s\n", __func__, ctx->username);
2178
2179 len = key->datalen - (len + 1);
2180 if (len > CIFS_MAX_PASSWORD_LEN || len <= 0) {
2181 cifs_dbg(FYI, "Bad len for password search (len=%zd)\n", len);
2182 rc = -EINVAL;
2183 kfree(ctx->username);
2184 ctx->username = NULL;
2185 goto out_key_put;
2186 }
2187
2188 ++delim;
2189 ctx->password = kstrndup(delim, len, GFP_KERNEL);
2190 if (!ctx->password) {
2191 cifs_dbg(FYI, "Unable to allocate %zd bytes for password\n",
2192 len);
2193 rc = -ENOMEM;
2194 kfree(ctx->username);
2195 ctx->username = NULL;
2196 goto out_key_put;
2197 }
2198
2199 /*
2200 * If we have a domain key then we must set the domainName in the
2201 * for the request.
2202 */
2203 if (is_domain && ses->domainName) {
2204 ctx->domainname = kstrdup(ses->domainName, GFP_KERNEL);
2205 if (!ctx->domainname) {
2206 cifs_dbg(FYI, "Unable to allocate %zd bytes for domain\n",
2207 len);
2208 rc = -ENOMEM;
2209 kfree(ctx->username);
2210 ctx->username = NULL;
2211 kfree_sensitive(ctx->password);
2212 ctx->password = NULL;
2213 goto out_key_put;
2214 }
2215 }
2216
2217 strscpy(ctx->workstation_name, ses->workstation_name, sizeof(ctx->workstation_name));
2218
2219out_key_put:
2220 up_read(&key->sem);
2221 key_put(key);
2222out_err:
2223 kfree(desc);
2224 cifs_dbg(FYI, "%s: returning %d\n", __func__, rc);
2225 return rc;
2226}
2227#else /* ! CONFIG_KEYS */
2228static inline int
2229cifs_set_cifscreds(struct smb3_fs_context *ctx __attribute__((unused)),
2230 struct cifs_ses *ses __attribute__((unused)))
2231{
2232 return -ENOSYS;
2233}
2234#endif /* CONFIG_KEYS */
2235
2236/**
2237 * cifs_get_smb_ses - get a session matching @ctx data from @server
2238 * @server: server to setup the session to
2239 * @ctx: superblock configuration context to use to setup the session
2240 *
2241 * This function assumes it is being called from cifs_mount() where we
2242 * already got a server reference (server refcount +1). See
2243 * cifs_get_tcon() for refcount explanations.
2244 */
2245struct cifs_ses *
2246cifs_get_smb_ses(struct TCP_Server_Info *server, struct smb3_fs_context *ctx)
2247{
2248 int rc = 0;
2249 unsigned int xid;
2250 struct cifs_ses *ses;
2251 struct sockaddr_in *addr = (struct sockaddr_in *)&server->dstaddr;
2252 struct sockaddr_in6 *addr6 = (struct sockaddr_in6 *)&server->dstaddr;
2253
2254 xid = get_xid();
2255
2256 ses = cifs_find_smb_ses(server, ctx);
2257 if (ses) {
2258 cifs_dbg(FYI, "Existing smb sess found (status=%d)\n",
2259 ses->ses_status);
2260
2261 spin_lock(&ses->chan_lock);
2262 if (cifs_chan_needs_reconnect(ses, server)) {
2263 spin_unlock(&ses->chan_lock);
2264 cifs_dbg(FYI, "Session needs reconnect\n");
2265
2266 mutex_lock(&ses->session_mutex);
2267 rc = cifs_negotiate_protocol(xid, ses, server);
2268 if (rc) {
2269 mutex_unlock(&ses->session_mutex);
2270 /* problem -- put our ses reference */
2271 cifs_put_smb_ses(ses);
2272 free_xid(xid);
2273 return ERR_PTR(rc);
2274 }
2275
2276 rc = cifs_setup_session(xid, ses, server,
2277 ctx->local_nls);
2278 if (rc) {
2279 mutex_unlock(&ses->session_mutex);
2280 /* problem -- put our reference */
2281 cifs_put_smb_ses(ses);
2282 free_xid(xid);
2283 return ERR_PTR(rc);
2284 }
2285 mutex_unlock(&ses->session_mutex);
2286
2287 spin_lock(&ses->chan_lock);
2288 }
2289 spin_unlock(&ses->chan_lock);
2290
2291 /* existing SMB ses has a server reference already */
2292 cifs_put_tcp_session(server, 0);
2293 free_xid(xid);
2294 return ses;
2295 }
2296
2297 rc = -ENOMEM;
2298
2299 cifs_dbg(FYI, "Existing smb sess not found\n");
2300 ses = sesInfoAlloc();
2301 if (ses == NULL)
2302 goto get_ses_fail;
2303
2304 /* new SMB session uses our server ref */
2305 ses->server = server;
2306 if (server->dstaddr.ss_family == AF_INET6)
2307 sprintf(ses->ip_addr, "%pI6", &addr6->sin6_addr);
2308 else
2309 sprintf(ses->ip_addr, "%pI4", &addr->sin_addr);
2310
2311 if (ctx->username) {
2312 ses->user_name = kstrdup(ctx->username, GFP_KERNEL);
2313 if (!ses->user_name)
2314 goto get_ses_fail;
2315 }
2316
2317 /* ctx->password freed at unmount */
2318 if (ctx->password) {
2319 ses->password = kstrdup(ctx->password, GFP_KERNEL);
2320 if (!ses->password)
2321 goto get_ses_fail;
2322 }
2323 if (ctx->domainname) {
2324 ses->domainName = kstrdup(ctx->domainname, GFP_KERNEL);
2325 if (!ses->domainName)
2326 goto get_ses_fail;
2327 }
2328
2329 strscpy(ses->workstation_name, ctx->workstation_name, sizeof(ses->workstation_name));
2330
2331 if (ctx->domainauto)
2332 ses->domainAuto = ctx->domainauto;
2333 ses->cred_uid = ctx->cred_uid;
2334 ses->linux_uid = ctx->linux_uid;
2335
2336 ses->sectype = ctx->sectype;
2337 ses->sign = ctx->sign;
2338 ses->local_nls = load_nls(ctx->local_nls->charset);
2339
2340 /* add server as first channel */
2341 spin_lock(&ses->chan_lock);
2342 ses->chans[0].server = server;
2343 ses->chan_count = 1;
2344 ses->chan_max = ctx->multichannel ? ctx->max_channels:1;
2345 ses->chans_need_reconnect = 1;
2346 spin_unlock(&ses->chan_lock);
2347
2348 mutex_lock(&ses->session_mutex);
2349 rc = cifs_negotiate_protocol(xid, ses, server);
2350 if (!rc)
2351 rc = cifs_setup_session(xid, ses, server, ctx->local_nls);
2352 mutex_unlock(&ses->session_mutex);
2353
2354 /* each channel uses a different signing key */
2355 spin_lock(&ses->chan_lock);
2356 memcpy(ses->chans[0].signkey, ses->smb3signingkey,
2357 sizeof(ses->smb3signingkey));
2358 spin_unlock(&ses->chan_lock);
2359
2360 if (rc)
2361 goto get_ses_fail;
2362
2363 /*
2364 * success, put it on the list and add it as first channel
2365 * note: the session becomes active soon after this. So you'll
2366 * need to lock before changing something in the session.
2367 */
2368 spin_lock(&cifs_tcp_ses_lock);
2369 ses->dfs_root_ses = ctx->dfs_root_ses;
2370 if (ses->dfs_root_ses)
2371 ses->dfs_root_ses->ses_count++;
2372 list_add(&ses->smb_ses_list, &server->smb_ses_list);
2373 spin_unlock(&cifs_tcp_ses_lock);
2374
2375 cifs_setup_ipc(ses, ctx);
2376
2377 free_xid(xid);
2378
2379 return ses;
2380
2381get_ses_fail:
2382 sesInfoFree(ses);
2383 free_xid(xid);
2384 return ERR_PTR(rc);
2385}
2386
2387/* this function must be called with tc_lock held */
2388static int match_tcon(struct cifs_tcon *tcon, struct smb3_fs_context *ctx)
2389{
2390 struct TCP_Server_Info *server = tcon->ses->server;
2391
2392 if (tcon->status == TID_EXITING)
2393 return 0;
2394
2395 if (tcon->origin_fullpath) {
2396 if (!ctx->source ||
2397 !dfs_src_pathname_equal(ctx->source,
2398 tcon->origin_fullpath))
2399 return 0;
2400 } else if (!server->leaf_fullpath &&
2401 strncmp(tcon->tree_name, ctx->UNC, MAX_TREE_SIZE)) {
2402 return 0;
2403 }
2404 if (tcon->seal != ctx->seal)
2405 return 0;
2406 if (tcon->snapshot_time != ctx->snapshot_time)
2407 return 0;
2408 if (tcon->handle_timeout != ctx->handle_timeout)
2409 return 0;
2410 if (tcon->no_lease != ctx->no_lease)
2411 return 0;
2412 if (tcon->nodelete != ctx->nodelete)
2413 return 0;
2414 return 1;
2415}
2416
2417static struct cifs_tcon *
2418cifs_find_tcon(struct cifs_ses *ses, struct smb3_fs_context *ctx)
2419{
2420 struct cifs_tcon *tcon;
2421
2422 spin_lock(&cifs_tcp_ses_lock);
2423 list_for_each_entry(tcon, &ses->tcon_list, tcon_list) {
2424 spin_lock(&tcon->tc_lock);
2425 if (!match_tcon(tcon, ctx)) {
2426 spin_unlock(&tcon->tc_lock);
2427 continue;
2428 }
2429 ++tcon->tc_count;
2430 spin_unlock(&tcon->tc_lock);
2431 spin_unlock(&cifs_tcp_ses_lock);
2432 return tcon;
2433 }
2434 spin_unlock(&cifs_tcp_ses_lock);
2435 return NULL;
2436}
2437
2438void
2439cifs_put_tcon(struct cifs_tcon *tcon)
2440{
2441 unsigned int xid;
2442 struct cifs_ses *ses;
2443
2444 /*
2445 * IPC tcon share the lifetime of their session and are
2446 * destroyed in the session put function
2447 */
2448 if (tcon == NULL || tcon->ipc)
2449 return;
2450
2451 ses = tcon->ses;
2452 cifs_dbg(FYI, "%s: tc_count=%d\n", __func__, tcon->tc_count);
2453 spin_lock(&cifs_tcp_ses_lock);
2454 spin_lock(&tcon->tc_lock);
2455 if (--tcon->tc_count > 0) {
2456 spin_unlock(&tcon->tc_lock);
2457 spin_unlock(&cifs_tcp_ses_lock);
2458 return;
2459 }
2460
2461 /* tc_count can never go negative */
2462 WARN_ON(tcon->tc_count < 0);
2463
2464 list_del_init(&tcon->tcon_list);
2465 tcon->status = TID_EXITING;
2466 spin_unlock(&tcon->tc_lock);
2467 spin_unlock(&cifs_tcp_ses_lock);
2468
2469 /* cancel polling of interfaces */
2470 cancel_delayed_work_sync(&tcon->query_interfaces);
2471#ifdef CONFIG_CIFS_DFS_UPCALL
2472 cancel_delayed_work_sync(&tcon->dfs_cache_work);
2473#endif
2474
2475 if (tcon->use_witness) {
2476 int rc;
2477
2478 rc = cifs_swn_unregister(tcon);
2479 if (rc < 0) {
2480 cifs_dbg(VFS, "%s: Failed to unregister for witness notifications: %d\n",
2481 __func__, rc);
2482 }
2483 }
2484
2485 xid = get_xid();
2486 if (ses->server->ops->tree_disconnect)
2487 ses->server->ops->tree_disconnect(xid, tcon);
2488 _free_xid(xid);
2489
2490 cifs_fscache_release_super_cookie(tcon);
2491 tconInfoFree(tcon);
2492 cifs_put_smb_ses(ses);
2493}
2494
2495/**
2496 * cifs_get_tcon - get a tcon matching @ctx data from @ses
2497 * @ses: smb session to issue the request on
2498 * @ctx: the superblock configuration context to use for building the
2499 *
2500 * - tcon refcount is the number of mount points using the tcon.
2501 * - ses refcount is the number of tcon using the session.
2502 *
2503 * 1. This function assumes it is being called from cifs_mount() where
2504 * we already got a session reference (ses refcount +1).
2505 *
2506 * 2. Since we're in the context of adding a mount point, the end
2507 * result should be either:
2508 *
2509 * a) a new tcon already allocated with refcount=1 (1 mount point) and
2510 * its session refcount incremented (1 new tcon). This +1 was
2511 * already done in (1).
2512 *
2513 * b) an existing tcon with refcount+1 (add a mount point to it) and
2514 * identical ses refcount (no new tcon). Because of (1) we need to
2515 * decrement the ses refcount.
2516 */
2517static struct cifs_tcon *
2518cifs_get_tcon(struct cifs_ses *ses, struct smb3_fs_context *ctx)
2519{
2520 struct cifs_tcon *tcon;
2521 bool nohandlecache;
2522 int rc, xid;
2523
2524 tcon = cifs_find_tcon(ses, ctx);
2525 if (tcon) {
2526 /*
2527 * tcon has refcount already incremented but we need to
2528 * decrement extra ses reference gotten by caller (case b)
2529 */
2530 cifs_dbg(FYI, "Found match on UNC path\n");
2531 cifs_put_smb_ses(ses);
2532 return tcon;
2533 }
2534
2535 if (!ses->server->ops->tree_connect) {
2536 rc = -ENOSYS;
2537 goto out_fail;
2538 }
2539
2540 if (ses->server->dialect >= SMB20_PROT_ID &&
2541 (ses->server->capabilities & SMB2_GLOBAL_CAP_DIRECTORY_LEASING))
2542 nohandlecache = ctx->nohandlecache;
2543 else
2544 nohandlecache = true;
2545 tcon = tcon_info_alloc(!nohandlecache);
2546 if (tcon == NULL) {
2547 rc = -ENOMEM;
2548 goto out_fail;
2549 }
2550 tcon->nohandlecache = nohandlecache;
2551
2552 if (ctx->snapshot_time) {
2553 if (ses->server->vals->protocol_id == 0) {
2554 cifs_dbg(VFS,
2555 "Use SMB2 or later for snapshot mount option\n");
2556 rc = -EOPNOTSUPP;
2557 goto out_fail;
2558 } else
2559 tcon->snapshot_time = ctx->snapshot_time;
2560 }
2561
2562 if (ctx->handle_timeout) {
2563 if (ses->server->vals->protocol_id == 0) {
2564 cifs_dbg(VFS,
2565 "Use SMB2.1 or later for handle timeout option\n");
2566 rc = -EOPNOTSUPP;
2567 goto out_fail;
2568 } else
2569 tcon->handle_timeout = ctx->handle_timeout;
2570 }
2571
2572 tcon->ses = ses;
2573 if (ctx->password) {
2574 tcon->password = kstrdup(ctx->password, GFP_KERNEL);
2575 if (!tcon->password) {
2576 rc = -ENOMEM;
2577 goto out_fail;
2578 }
2579 }
2580
2581 if (ctx->seal) {
2582 if (ses->server->vals->protocol_id == 0) {
2583 cifs_dbg(VFS,
2584 "SMB3 or later required for encryption\n");
2585 rc = -EOPNOTSUPP;
2586 goto out_fail;
2587 } else if (tcon->ses->server->capabilities &
2588 SMB2_GLOBAL_CAP_ENCRYPTION)
2589 tcon->seal = true;
2590 else {
2591 cifs_dbg(VFS, "Encryption is not supported on share\n");
2592 rc = -EOPNOTSUPP;
2593 goto out_fail;
2594 }
2595 }
2596
2597 if (ctx->linux_ext) {
2598 if (ses->server->posix_ext_supported) {
2599 tcon->posix_extensions = true;
2600 pr_warn_once("SMB3.11 POSIX Extensions are experimental\n");
2601 } else if ((ses->server->vals->protocol_id == SMB311_PROT_ID) ||
2602 (strcmp(ses->server->vals->version_string,
2603 SMB3ANY_VERSION_STRING) == 0) ||
2604 (strcmp(ses->server->vals->version_string,
2605 SMBDEFAULT_VERSION_STRING) == 0)) {
2606 cifs_dbg(VFS, "Server does not support mounting with posix SMB3.11 extensions\n");
2607 rc = -EOPNOTSUPP;
2608 goto out_fail;
2609 } else {
2610 cifs_dbg(VFS,
2611 "Check vers= mount option. SMB3.11 disabled but required for POSIX extensions\n");
2612 rc = -EOPNOTSUPP;
2613 goto out_fail;
2614 }
2615 }
2616
2617 xid = get_xid();
2618 rc = ses->server->ops->tree_connect(xid, ses, ctx->UNC, tcon,
2619 ctx->local_nls);
2620 free_xid(xid);
2621 cifs_dbg(FYI, "Tcon rc = %d\n", rc);
2622 if (rc)
2623 goto out_fail;
2624
2625 tcon->use_persistent = false;
2626 /* check if SMB2 or later, CIFS does not support persistent handles */
2627 if (ctx->persistent) {
2628 if (ses->server->vals->protocol_id == 0) {
2629 cifs_dbg(VFS,
2630 "SMB3 or later required for persistent handles\n");
2631 rc = -EOPNOTSUPP;
2632 goto out_fail;
2633 } else if (ses->server->capabilities &
2634 SMB2_GLOBAL_CAP_PERSISTENT_HANDLES)
2635 tcon->use_persistent = true;
2636 else /* persistent handles requested but not supported */ {
2637 cifs_dbg(VFS,
2638 "Persistent handles not supported on share\n");
2639 rc = -EOPNOTSUPP;
2640 goto out_fail;
2641 }
2642 } else if ((tcon->capabilities & SMB2_SHARE_CAP_CONTINUOUS_AVAILABILITY)
2643 && (ses->server->capabilities & SMB2_GLOBAL_CAP_PERSISTENT_HANDLES)
2644 && (ctx->nopersistent == false)) {
2645 cifs_dbg(FYI, "enabling persistent handles\n");
2646 tcon->use_persistent = true;
2647 } else if (ctx->resilient) {
2648 if (ses->server->vals->protocol_id == 0) {
2649 cifs_dbg(VFS,
2650 "SMB2.1 or later required for resilient handles\n");
2651 rc = -EOPNOTSUPP;
2652 goto out_fail;
2653 }
2654 tcon->use_resilient = true;
2655 }
2656
2657 tcon->use_witness = false;
2658 if (IS_ENABLED(CONFIG_CIFS_SWN_UPCALL) && ctx->witness) {
2659 if (ses->server->vals->protocol_id >= SMB30_PROT_ID) {
2660 if (tcon->capabilities & SMB2_SHARE_CAP_CLUSTER) {
2661 /*
2662 * Set witness in use flag in first place
2663 * to retry registration in the echo task
2664 */
2665 tcon->use_witness = true;
2666 /* And try to register immediately */
2667 rc = cifs_swn_register(tcon);
2668 if (rc < 0) {
2669 cifs_dbg(VFS, "Failed to register for witness notifications: %d\n", rc);
2670 goto out_fail;
2671 }
2672 } else {
2673 /* TODO: try to extend for non-cluster uses (eg multichannel) */
2674 cifs_dbg(VFS, "witness requested on mount but no CLUSTER capability on share\n");
2675 rc = -EOPNOTSUPP;
2676 goto out_fail;
2677 }
2678 } else {
2679 cifs_dbg(VFS, "SMB3 or later required for witness option\n");
2680 rc = -EOPNOTSUPP;
2681 goto out_fail;
2682 }
2683 }
2684
2685 /* If the user really knows what they are doing they can override */
2686 if (tcon->share_flags & SMB2_SHAREFLAG_NO_CACHING) {
2687 if (ctx->cache_ro)
2688 cifs_dbg(VFS, "cache=ro requested on mount but NO_CACHING flag set on share\n");
2689 else if (ctx->cache_rw)
2690 cifs_dbg(VFS, "cache=singleclient requested on mount but NO_CACHING flag set on share\n");
2691 }
2692
2693 if (ctx->no_lease) {
2694 if (ses->server->vals->protocol_id == 0) {
2695 cifs_dbg(VFS,
2696 "SMB2 or later required for nolease option\n");
2697 rc = -EOPNOTSUPP;
2698 goto out_fail;
2699 } else
2700 tcon->no_lease = ctx->no_lease;
2701 }
2702
2703 /*
2704 * We can have only one retry value for a connection to a share so for
2705 * resources mounted more than once to the same server share the last
2706 * value passed in for the retry flag is used.
2707 */
2708 tcon->retry = ctx->retry;
2709 tcon->nocase = ctx->nocase;
2710 tcon->broken_sparse_sup = ctx->no_sparse;
2711 tcon->max_cached_dirs = ctx->max_cached_dirs;
2712 tcon->nodelete = ctx->nodelete;
2713 tcon->local_lease = ctx->local_lease;
2714 INIT_LIST_HEAD(&tcon->pending_opens);
2715 tcon->status = TID_GOOD;
2716
2717 INIT_DELAYED_WORK(&tcon->query_interfaces,
2718 smb2_query_server_interfaces);
2719 if (ses->server->dialect >= SMB30_PROT_ID &&
2720 (ses->server->capabilities & SMB2_GLOBAL_CAP_MULTI_CHANNEL)) {
2721 /* schedule query interfaces poll */
2722 queue_delayed_work(cifsiod_wq, &tcon->query_interfaces,
2723 (SMB_INTERFACE_POLL_INTERVAL * HZ));
2724 }
2725#ifdef CONFIG_CIFS_DFS_UPCALL
2726 INIT_DELAYED_WORK(&tcon->dfs_cache_work, dfs_cache_refresh);
2727#endif
2728 spin_lock(&cifs_tcp_ses_lock);
2729 list_add(&tcon->tcon_list, &ses->tcon_list);
2730 spin_unlock(&cifs_tcp_ses_lock);
2731
2732 return tcon;
2733
2734out_fail:
2735 tconInfoFree(tcon);
2736 return ERR_PTR(rc);
2737}
2738
2739void
2740cifs_put_tlink(struct tcon_link *tlink)
2741{
2742 if (!tlink || IS_ERR(tlink))
2743 return;
2744
2745 if (!atomic_dec_and_test(&tlink->tl_count) ||
2746 test_bit(TCON_LINK_IN_TREE, &tlink->tl_flags)) {
2747 tlink->tl_time = jiffies;
2748 return;
2749 }
2750
2751 if (!IS_ERR(tlink_tcon(tlink)))
2752 cifs_put_tcon(tlink_tcon(tlink));
2753 kfree(tlink);
2754}
2755
2756static int
2757compare_mount_options(struct super_block *sb, struct cifs_mnt_data *mnt_data)
2758{
2759 struct cifs_sb_info *old = CIFS_SB(sb);
2760 struct cifs_sb_info *new = mnt_data->cifs_sb;
2761 unsigned int oldflags = old->mnt_cifs_flags & CIFS_MOUNT_MASK;
2762 unsigned int newflags = new->mnt_cifs_flags & CIFS_MOUNT_MASK;
2763
2764 if ((sb->s_flags & CIFS_MS_MASK) != (mnt_data->flags & CIFS_MS_MASK))
2765 return 0;
2766
2767 if (old->mnt_cifs_serverino_autodisabled)
2768 newflags &= ~CIFS_MOUNT_SERVER_INUM;
2769
2770 if (oldflags != newflags)
2771 return 0;
2772
2773 /*
2774 * We want to share sb only if we don't specify an r/wsize or
2775 * specified r/wsize is greater than or equal to existing one.
2776 */
2777 if (new->ctx->wsize && new->ctx->wsize < old->ctx->wsize)
2778 return 0;
2779
2780 if (new->ctx->rsize && new->ctx->rsize < old->ctx->rsize)
2781 return 0;
2782
2783 if (!uid_eq(old->ctx->linux_uid, new->ctx->linux_uid) ||
2784 !gid_eq(old->ctx->linux_gid, new->ctx->linux_gid))
2785 return 0;
2786
2787 if (old->ctx->file_mode != new->ctx->file_mode ||
2788 old->ctx->dir_mode != new->ctx->dir_mode)
2789 return 0;
2790
2791 if (strcmp(old->local_nls->charset, new->local_nls->charset))
2792 return 0;
2793
2794 if (old->ctx->acregmax != new->ctx->acregmax)
2795 return 0;
2796 if (old->ctx->acdirmax != new->ctx->acdirmax)
2797 return 0;
2798 if (old->ctx->closetimeo != new->ctx->closetimeo)
2799 return 0;
2800
2801 return 1;
2802}
2803
2804static int match_prepath(struct super_block *sb,
2805 struct cifs_tcon *tcon,
2806 struct cifs_mnt_data *mnt_data)
2807{
2808 struct smb3_fs_context *ctx = mnt_data->ctx;
2809 struct cifs_sb_info *old = CIFS_SB(sb);
2810 struct cifs_sb_info *new = mnt_data->cifs_sb;
2811 bool old_set = (old->mnt_cifs_flags & CIFS_MOUNT_USE_PREFIX_PATH) &&
2812 old->prepath;
2813 bool new_set = (new->mnt_cifs_flags & CIFS_MOUNT_USE_PREFIX_PATH) &&
2814 new->prepath;
2815
2816 if (tcon->origin_fullpath &&
2817 dfs_src_pathname_equal(tcon->origin_fullpath, ctx->source))
2818 return 1;
2819
2820 if (old_set && new_set && !strcmp(new->prepath, old->prepath))
2821 return 1;
2822 else if (!old_set && !new_set)
2823 return 1;
2824
2825 return 0;
2826}
2827
2828int
2829cifs_match_super(struct super_block *sb, void *data)
2830{
2831 struct cifs_mnt_data *mnt_data = data;
2832 struct smb3_fs_context *ctx;
2833 struct cifs_sb_info *cifs_sb;
2834 struct TCP_Server_Info *tcp_srv;
2835 struct cifs_ses *ses;
2836 struct cifs_tcon *tcon;
2837 struct tcon_link *tlink;
2838 int rc = 0;
2839
2840 spin_lock(&cifs_tcp_ses_lock);
2841 cifs_sb = CIFS_SB(sb);
2842
2843 /* We do not want to use a superblock that has been shutdown */
2844 if (CIFS_MOUNT_SHUTDOWN & cifs_sb->mnt_cifs_flags) {
2845 spin_unlock(&cifs_tcp_ses_lock);
2846 return 0;
2847 }
2848
2849 tlink = cifs_get_tlink(cifs_sb_master_tlink(cifs_sb));
2850 if (IS_ERR_OR_NULL(tlink)) {
2851 pr_warn_once("%s: skip super matching due to bad tlink(%p)\n",
2852 __func__, tlink);
2853 spin_unlock(&cifs_tcp_ses_lock);
2854 return 0;
2855 }
2856 tcon = tlink_tcon(tlink);
2857 ses = tcon->ses;
2858 tcp_srv = ses->server;
2859
2860 ctx = mnt_data->ctx;
2861
2862 spin_lock(&tcp_srv->srv_lock);
2863 spin_lock(&ses->ses_lock);
2864 spin_lock(&ses->chan_lock);
2865 spin_lock(&tcon->tc_lock);
2866 if (!match_server(tcp_srv, ctx, true) ||
2867 !match_session(ses, ctx) ||
2868 !match_tcon(tcon, ctx) ||
2869 !match_prepath(sb, tcon, mnt_data)) {
2870 rc = 0;
2871 goto out;
2872 }
2873
2874 rc = compare_mount_options(sb, mnt_data);
2875out:
2876 spin_unlock(&tcon->tc_lock);
2877 spin_unlock(&ses->chan_lock);
2878 spin_unlock(&ses->ses_lock);
2879 spin_unlock(&tcp_srv->srv_lock);
2880
2881 spin_unlock(&cifs_tcp_ses_lock);
2882 cifs_put_tlink(tlink);
2883 return rc;
2884}
2885
2886#ifdef CONFIG_DEBUG_LOCK_ALLOC
2887static struct lock_class_key cifs_key[2];
2888static struct lock_class_key cifs_slock_key[2];
2889
2890static inline void
2891cifs_reclassify_socket4(struct socket *sock)
2892{
2893 struct sock *sk = sock->sk;
2894
2895 BUG_ON(!sock_allow_reclassification(sk));
2896 sock_lock_init_class_and_name(sk, "slock-AF_INET-CIFS",
2897 &cifs_slock_key[0], "sk_lock-AF_INET-CIFS", &cifs_key[0]);
2898}
2899
2900static inline void
2901cifs_reclassify_socket6(struct socket *sock)
2902{
2903 struct sock *sk = sock->sk;
2904
2905 BUG_ON(!sock_allow_reclassification(sk));
2906 sock_lock_init_class_and_name(sk, "slock-AF_INET6-CIFS",
2907 &cifs_slock_key[1], "sk_lock-AF_INET6-CIFS", &cifs_key[1]);
2908}
2909#else
2910static inline void
2911cifs_reclassify_socket4(struct socket *sock)
2912{
2913}
2914
2915static inline void
2916cifs_reclassify_socket6(struct socket *sock)
2917{
2918}
2919#endif
2920
2921/* See RFC1001 section 14 on representation of Netbios names */
2922static void rfc1002mangle(char *target, char *source, unsigned int length)
2923{
2924 unsigned int i, j;
2925
2926 for (i = 0, j = 0; i < (length); i++) {
2927 /* mask a nibble at a time and encode */
2928 target[j] = 'A' + (0x0F & (source[i] >> 4));
2929 target[j+1] = 'A' + (0x0F & source[i]);
2930 j += 2;
2931 }
2932
2933}
2934
2935static int
2936bind_socket(struct TCP_Server_Info *server)
2937{
2938 int rc = 0;
2939
2940 if (server->srcaddr.ss_family != AF_UNSPEC) {
2941 /* Bind to the specified local IP address */
2942 struct socket *socket = server->ssocket;
2943
2944 rc = kernel_bind(socket,
2945 (struct sockaddr *) &server->srcaddr,
2946 sizeof(server->srcaddr));
2947 if (rc < 0) {
2948 struct sockaddr_in *saddr4;
2949 struct sockaddr_in6 *saddr6;
2950
2951 saddr4 = (struct sockaddr_in *)&server->srcaddr;
2952 saddr6 = (struct sockaddr_in6 *)&server->srcaddr;
2953 if (saddr6->sin6_family == AF_INET6)
2954 cifs_server_dbg(VFS, "Failed to bind to: %pI6c, error: %d\n",
2955 &saddr6->sin6_addr, rc);
2956 else
2957 cifs_server_dbg(VFS, "Failed to bind to: %pI4, error: %d\n",
2958 &saddr4->sin_addr.s_addr, rc);
2959 }
2960 }
2961 return rc;
2962}
2963
2964static int
2965ip_rfc1001_connect(struct TCP_Server_Info *server)
2966{
2967 int rc = 0;
2968 /*
2969 * some servers require RFC1001 sessinit before sending
2970 * negprot - BB check reconnection in case where second
2971 * sessinit is sent but no second negprot
2972 */
2973 struct rfc1002_session_packet req = {};
2974 struct smb_hdr *smb_buf = (struct smb_hdr *)&req;
2975 unsigned int len;
2976
2977 req.trailer.session_req.called_len = sizeof(req.trailer.session_req.called_name);
2978
2979 if (server->server_RFC1001_name[0] != 0)
2980 rfc1002mangle(req.trailer.session_req.called_name,
2981 server->server_RFC1001_name,
2982 RFC1001_NAME_LEN_WITH_NULL);
2983 else
2984 rfc1002mangle(req.trailer.session_req.called_name,
2985 DEFAULT_CIFS_CALLED_NAME,
2986 RFC1001_NAME_LEN_WITH_NULL);
2987
2988 req.trailer.session_req.calling_len = sizeof(req.trailer.session_req.calling_name);
2989
2990 /* calling name ends in null (byte 16) from old smb convention */
2991 if (server->workstation_RFC1001_name[0] != 0)
2992 rfc1002mangle(req.trailer.session_req.calling_name,
2993 server->workstation_RFC1001_name,
2994 RFC1001_NAME_LEN_WITH_NULL);
2995 else
2996 rfc1002mangle(req.trailer.session_req.calling_name,
2997 "LINUX_CIFS_CLNT",
2998 RFC1001_NAME_LEN_WITH_NULL);
2999
3000 /*
3001 * As per rfc1002, @len must be the number of bytes that follows the
3002 * length field of a rfc1002 session request payload.
3003 */
3004 len = sizeof(req) - offsetof(struct rfc1002_session_packet, trailer.session_req);
3005
3006 smb_buf->smb_buf_length = cpu_to_be32((RFC1002_SESSION_REQUEST << 24) | len);
3007 rc = smb_send(server, smb_buf, len);
3008 /*
3009 * RFC1001 layer in at least one server requires very short break before
3010 * negprot presumably because not expecting negprot to follow so fast.
3011 * This is a simple solution that works without complicating the code
3012 * and causes no significant slowing down on mount for everyone else
3013 */
3014 usleep_range(1000, 2000);
3015
3016 return rc;
3017}
3018
3019static int
3020generic_ip_connect(struct TCP_Server_Info *server)
3021{
3022 struct sockaddr *saddr;
3023 struct socket *socket;
3024 int slen, sfamily;
3025 __be16 sport;
3026 int rc = 0;
3027
3028 saddr = (struct sockaddr *) &server->dstaddr;
3029
3030 if (server->dstaddr.ss_family == AF_INET6) {
3031 struct sockaddr_in6 *ipv6 = (struct sockaddr_in6 *)&server->dstaddr;
3032
3033 sport = ipv6->sin6_port;
3034 slen = sizeof(struct sockaddr_in6);
3035 sfamily = AF_INET6;
3036 cifs_dbg(FYI, "%s: connecting to [%pI6]:%d\n", __func__, &ipv6->sin6_addr,
3037 ntohs(sport));
3038 } else {
3039 struct sockaddr_in *ipv4 = (struct sockaddr_in *)&server->dstaddr;
3040
3041 sport = ipv4->sin_port;
3042 slen = sizeof(struct sockaddr_in);
3043 sfamily = AF_INET;
3044 cifs_dbg(FYI, "%s: connecting to %pI4:%d\n", __func__, &ipv4->sin_addr,
3045 ntohs(sport));
3046 }
3047
3048 if (server->ssocket) {
3049 socket = server->ssocket;
3050 } else {
3051 rc = __sock_create(cifs_net_ns(server), sfamily, SOCK_STREAM,
3052 IPPROTO_TCP, &server->ssocket, 1);
3053 if (rc < 0) {
3054 cifs_server_dbg(VFS, "Error %d creating socket\n", rc);
3055 return rc;
3056 }
3057
3058 /* BB other socket options to set KEEPALIVE, NODELAY? */
3059 cifs_dbg(FYI, "Socket created\n");
3060 socket = server->ssocket;
3061 socket->sk->sk_allocation = GFP_NOFS;
3062 socket->sk->sk_use_task_frag = false;
3063 if (sfamily == AF_INET6)
3064 cifs_reclassify_socket6(socket);
3065 else
3066 cifs_reclassify_socket4(socket);
3067 }
3068
3069 rc = bind_socket(server);
3070 if (rc < 0)
3071 return rc;
3072
3073 /*
3074 * Eventually check for other socket options to change from
3075 * the default. sock_setsockopt not used because it expects
3076 * user space buffer
3077 */
3078 socket->sk->sk_rcvtimeo = 7 * HZ;
3079 socket->sk->sk_sndtimeo = 5 * HZ;
3080
3081 /* make the bufsizes depend on wsize/rsize and max requests */
3082 if (server->noautotune) {
3083 if (socket->sk->sk_sndbuf < (200 * 1024))
3084 socket->sk->sk_sndbuf = 200 * 1024;
3085 if (socket->sk->sk_rcvbuf < (140 * 1024))
3086 socket->sk->sk_rcvbuf = 140 * 1024;
3087 }
3088
3089 if (server->tcp_nodelay)
3090 tcp_sock_set_nodelay(socket->sk);
3091
3092 cifs_dbg(FYI, "sndbuf %d rcvbuf %d rcvtimeo 0x%lx\n",
3093 socket->sk->sk_sndbuf,
3094 socket->sk->sk_rcvbuf, socket->sk->sk_rcvtimeo);
3095
3096 rc = kernel_connect(socket, saddr, slen,
3097 server->noblockcnt ? O_NONBLOCK : 0);
3098 /*
3099 * When mounting SMB root file systems, we do not want to block in
3100 * connect. Otherwise bail out and then let cifs_reconnect() perform
3101 * reconnect failover - if possible.
3102 */
3103 if (server->noblockcnt && rc == -EINPROGRESS)
3104 rc = 0;
3105 if (rc < 0) {
3106 cifs_dbg(FYI, "Error %d connecting to server\n", rc);
3107 trace_smb3_connect_err(server->hostname, server->conn_id, &server->dstaddr, rc);
3108 sock_release(socket);
3109 server->ssocket = NULL;
3110 return rc;
3111 }
3112 trace_smb3_connect_done(server->hostname, server->conn_id, &server->dstaddr);
3113 if (sport == htons(RFC1001_PORT))
3114 rc = ip_rfc1001_connect(server);
3115
3116 return rc;
3117}
3118
3119static int
3120ip_connect(struct TCP_Server_Info *server)
3121{
3122 __be16 *sport;
3123 struct sockaddr_in6 *addr6 = (struct sockaddr_in6 *)&server->dstaddr;
3124 struct sockaddr_in *addr = (struct sockaddr_in *)&server->dstaddr;
3125
3126 if (server->dstaddr.ss_family == AF_INET6)
3127 sport = &addr6->sin6_port;
3128 else
3129 sport = &addr->sin_port;
3130
3131 if (*sport == 0) {
3132 int rc;
3133
3134 /* try with 445 port at first */
3135 *sport = htons(CIFS_PORT);
3136
3137 rc = generic_ip_connect(server);
3138 if (rc >= 0)
3139 return rc;
3140
3141 /* if it failed, try with 139 port */
3142 *sport = htons(RFC1001_PORT);
3143 }
3144
3145 return generic_ip_connect(server);
3146}
3147
3148#ifdef CONFIG_CIFS_ALLOW_INSECURE_LEGACY
3149void reset_cifs_unix_caps(unsigned int xid, struct cifs_tcon *tcon,
3150 struct cifs_sb_info *cifs_sb, struct smb3_fs_context *ctx)
3151{
3152 /*
3153 * If we are reconnecting then should we check to see if
3154 * any requested capabilities changed locally e.g. via
3155 * remount but we can not do much about it here
3156 * if they have (even if we could detect it by the following)
3157 * Perhaps we could add a backpointer to array of sb from tcon
3158 * or if we change to make all sb to same share the same
3159 * sb as NFS - then we only have one backpointer to sb.
3160 * What if we wanted to mount the server share twice once with
3161 * and once without posixacls or posix paths?
3162 */
3163 __u64 saved_cap = le64_to_cpu(tcon->fsUnixInfo.Capability);
3164
3165 if (ctx && ctx->no_linux_ext) {
3166 tcon->fsUnixInfo.Capability = 0;
3167 tcon->unix_ext = 0; /* Unix Extensions disabled */
3168 cifs_dbg(FYI, "Linux protocol extensions disabled\n");
3169 return;
3170 } else if (ctx)
3171 tcon->unix_ext = 1; /* Unix Extensions supported */
3172
3173 if (!tcon->unix_ext) {
3174 cifs_dbg(FYI, "Unix extensions disabled so not set on reconnect\n");
3175 return;
3176 }
3177
3178 if (!CIFSSMBQFSUnixInfo(xid, tcon)) {
3179 __u64 cap = le64_to_cpu(tcon->fsUnixInfo.Capability);
3180
3181 cifs_dbg(FYI, "unix caps which server supports %lld\n", cap);
3182 /*
3183 * check for reconnect case in which we do not
3184 * want to change the mount behavior if we can avoid it
3185 */
3186 if (ctx == NULL) {
3187 /*
3188 * turn off POSIX ACL and PATHNAMES if not set
3189 * originally at mount time
3190 */
3191 if ((saved_cap & CIFS_UNIX_POSIX_ACL_CAP) == 0)
3192 cap &= ~CIFS_UNIX_POSIX_ACL_CAP;
3193 if ((saved_cap & CIFS_UNIX_POSIX_PATHNAMES_CAP) == 0) {
3194 if (cap & CIFS_UNIX_POSIX_PATHNAMES_CAP)
3195 cifs_dbg(VFS, "POSIXPATH support change\n");
3196 cap &= ~CIFS_UNIX_POSIX_PATHNAMES_CAP;
3197 } else if ((cap & CIFS_UNIX_POSIX_PATHNAMES_CAP) == 0) {
3198 cifs_dbg(VFS, "possible reconnect error\n");
3199 cifs_dbg(VFS, "server disabled POSIX path support\n");
3200 }
3201 }
3202
3203 if (cap & CIFS_UNIX_TRANSPORT_ENCRYPTION_MANDATORY_CAP)
3204 cifs_dbg(VFS, "per-share encryption not supported yet\n");
3205
3206 cap &= CIFS_UNIX_CAP_MASK;
3207 if (ctx && ctx->no_psx_acl)
3208 cap &= ~CIFS_UNIX_POSIX_ACL_CAP;
3209 else if (CIFS_UNIX_POSIX_ACL_CAP & cap) {
3210 cifs_dbg(FYI, "negotiated posix acl support\n");
3211 if (cifs_sb)
3212 cifs_sb->mnt_cifs_flags |=
3213 CIFS_MOUNT_POSIXACL;
3214 }
3215
3216 if (ctx && ctx->posix_paths == 0)
3217 cap &= ~CIFS_UNIX_POSIX_PATHNAMES_CAP;
3218 else if (cap & CIFS_UNIX_POSIX_PATHNAMES_CAP) {
3219 cifs_dbg(FYI, "negotiate posix pathnames\n");
3220 if (cifs_sb)
3221 cifs_sb->mnt_cifs_flags |=
3222 CIFS_MOUNT_POSIX_PATHS;
3223 }
3224
3225 cifs_dbg(FYI, "Negotiate caps 0x%x\n", (int)cap);
3226#ifdef CONFIG_CIFS_DEBUG2
3227 if (cap & CIFS_UNIX_FCNTL_CAP)
3228 cifs_dbg(FYI, "FCNTL cap\n");
3229 if (cap & CIFS_UNIX_EXTATTR_CAP)
3230 cifs_dbg(FYI, "EXTATTR cap\n");
3231 if (cap & CIFS_UNIX_POSIX_PATHNAMES_CAP)
3232 cifs_dbg(FYI, "POSIX path cap\n");
3233 if (cap & CIFS_UNIX_XATTR_CAP)
3234 cifs_dbg(FYI, "XATTR cap\n");
3235 if (cap & CIFS_UNIX_POSIX_ACL_CAP)
3236 cifs_dbg(FYI, "POSIX ACL cap\n");
3237 if (cap & CIFS_UNIX_LARGE_READ_CAP)
3238 cifs_dbg(FYI, "very large read cap\n");
3239 if (cap & CIFS_UNIX_LARGE_WRITE_CAP)
3240 cifs_dbg(FYI, "very large write cap\n");
3241 if (cap & CIFS_UNIX_TRANSPORT_ENCRYPTION_CAP)
3242 cifs_dbg(FYI, "transport encryption cap\n");
3243 if (cap & CIFS_UNIX_TRANSPORT_ENCRYPTION_MANDATORY_CAP)
3244 cifs_dbg(FYI, "mandatory transport encryption cap\n");
3245#endif /* CIFS_DEBUG2 */
3246 if (CIFSSMBSetFSUnixInfo(xid, tcon, cap)) {
3247 if (ctx == NULL)
3248 cifs_dbg(FYI, "resetting capabilities failed\n");
3249 else
3250 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");
3251
3252 }
3253 }
3254}
3255#endif /* CONFIG_CIFS_ALLOW_INSECURE_LEGACY */
3256
3257int cifs_setup_cifs_sb(struct cifs_sb_info *cifs_sb)
3258{
3259 struct smb3_fs_context *ctx = cifs_sb->ctx;
3260
3261 INIT_DELAYED_WORK(&cifs_sb->prune_tlinks, cifs_prune_tlinks);
3262
3263 spin_lock_init(&cifs_sb->tlink_tree_lock);
3264 cifs_sb->tlink_tree = RB_ROOT;
3265
3266 cifs_dbg(FYI, "file mode: %04ho dir mode: %04ho\n",
3267 ctx->file_mode, ctx->dir_mode);
3268
3269 /* this is needed for ASCII cp to Unicode converts */
3270 if (ctx->iocharset == NULL) {
3271 /* load_nls_default cannot return null */
3272 cifs_sb->local_nls = load_nls_default();
3273 } else {
3274 cifs_sb->local_nls = load_nls(ctx->iocharset);
3275 if (cifs_sb->local_nls == NULL) {
3276 cifs_dbg(VFS, "CIFS mount error: iocharset %s not found\n",
3277 ctx->iocharset);
3278 return -ELIBACC;
3279 }
3280 }
3281 ctx->local_nls = cifs_sb->local_nls;
3282
3283 smb3_update_mnt_flags(cifs_sb);
3284
3285 if (ctx->direct_io)
3286 cifs_dbg(FYI, "mounting share using direct i/o\n");
3287 if (ctx->cache_ro) {
3288 cifs_dbg(VFS, "mounting share with read only caching. Ensure that the share will not be modified while in use.\n");
3289 cifs_sb->mnt_cifs_flags |= CIFS_MOUNT_RO_CACHE;
3290 } else if (ctx->cache_rw) {
3291 cifs_dbg(VFS, "mounting share in single client RW caching mode. Ensure that no other systems will be accessing the share.\n");
3292 cifs_sb->mnt_cifs_flags |= (CIFS_MOUNT_RO_CACHE |
3293 CIFS_MOUNT_RW_CACHE);
3294 }
3295
3296 if ((ctx->cifs_acl) && (ctx->dynperm))
3297 cifs_dbg(VFS, "mount option dynperm ignored if cifsacl mount option supported\n");
3298
3299 if (ctx->prepath) {
3300 cifs_sb->prepath = kstrdup(ctx->prepath, GFP_KERNEL);
3301 if (cifs_sb->prepath == NULL)
3302 return -ENOMEM;
3303 cifs_sb->mnt_cifs_flags |= CIFS_MOUNT_USE_PREFIX_PATH;
3304 }
3305
3306 return 0;
3307}
3308
3309/* Release all succeed connections */
3310void cifs_mount_put_conns(struct cifs_mount_ctx *mnt_ctx)
3311{
3312 int rc = 0;
3313
3314 if (mnt_ctx->tcon)
3315 cifs_put_tcon(mnt_ctx->tcon);
3316 else if (mnt_ctx->ses)
3317 cifs_put_smb_ses(mnt_ctx->ses);
3318 else if (mnt_ctx->server)
3319 cifs_put_tcp_session(mnt_ctx->server, 0);
3320 mnt_ctx->cifs_sb->mnt_cifs_flags &= ~CIFS_MOUNT_POSIX_PATHS;
3321 free_xid(mnt_ctx->xid);
3322}
3323
3324int cifs_mount_get_session(struct cifs_mount_ctx *mnt_ctx)
3325{
3326 struct TCP_Server_Info *server = NULL;
3327 struct smb3_fs_context *ctx;
3328 struct cifs_ses *ses = NULL;
3329 unsigned int xid;
3330 int rc = 0;
3331
3332 xid = get_xid();
3333
3334 if (WARN_ON_ONCE(!mnt_ctx || !mnt_ctx->fs_ctx)) {
3335 rc = -EINVAL;
3336 goto out;
3337 }
3338 ctx = mnt_ctx->fs_ctx;
3339
3340 /* get a reference to a tcp session */
3341 server = cifs_get_tcp_session(ctx, NULL);
3342 if (IS_ERR(server)) {
3343 rc = PTR_ERR(server);
3344 server = NULL;
3345 goto out;
3346 }
3347
3348 /* get a reference to a SMB session */
3349 ses = cifs_get_smb_ses(server, ctx);
3350 if (IS_ERR(ses)) {
3351 rc = PTR_ERR(ses);
3352 ses = NULL;
3353 goto out;
3354 }
3355
3356 if ((ctx->persistent == true) && (!(ses->server->capabilities &
3357 SMB2_GLOBAL_CAP_PERSISTENT_HANDLES))) {
3358 cifs_server_dbg(VFS, "persistent handles not supported by server\n");
3359 rc = -EOPNOTSUPP;
3360 }
3361
3362out:
3363 mnt_ctx->xid = xid;
3364 mnt_ctx->server = server;
3365 mnt_ctx->ses = ses;
3366 mnt_ctx->tcon = NULL;
3367
3368 return rc;
3369}
3370
3371int cifs_mount_get_tcon(struct cifs_mount_ctx *mnt_ctx)
3372{
3373 struct TCP_Server_Info *server;
3374 struct cifs_sb_info *cifs_sb;
3375 struct smb3_fs_context *ctx;
3376 struct cifs_tcon *tcon = NULL;
3377 int rc = 0;
3378
3379 if (WARN_ON_ONCE(!mnt_ctx || !mnt_ctx->server || !mnt_ctx->ses || !mnt_ctx->fs_ctx ||
3380 !mnt_ctx->cifs_sb)) {
3381 rc = -EINVAL;
3382 goto out;
3383 }
3384 server = mnt_ctx->server;
3385 ctx = mnt_ctx->fs_ctx;
3386 cifs_sb = mnt_ctx->cifs_sb;
3387
3388 /* search for existing tcon to this server share */
3389 tcon = cifs_get_tcon(mnt_ctx->ses, ctx);
3390 if (IS_ERR(tcon)) {
3391 rc = PTR_ERR(tcon);
3392 tcon = NULL;
3393 goto out;
3394 }
3395
3396 /* if new SMB3.11 POSIX extensions are supported do not remap / and \ */
3397 if (tcon->posix_extensions)
3398 cifs_sb->mnt_cifs_flags |= CIFS_MOUNT_POSIX_PATHS;
3399
3400#ifdef CONFIG_CIFS_ALLOW_INSECURE_LEGACY
3401 /* tell server which Unix caps we support */
3402 if (cap_unix(tcon->ses)) {
3403 /*
3404 * reset of caps checks mount to see if unix extensions disabled
3405 * for just this mount.
3406 */
3407 reset_cifs_unix_caps(mnt_ctx->xid, tcon, cifs_sb, ctx);
3408 spin_lock(&tcon->ses->server->srv_lock);
3409 if ((tcon->ses->server->tcpStatus == CifsNeedReconnect) &&
3410 (le64_to_cpu(tcon->fsUnixInfo.Capability) &
3411 CIFS_UNIX_TRANSPORT_ENCRYPTION_MANDATORY_CAP)) {
3412 spin_unlock(&tcon->ses->server->srv_lock);
3413 rc = -EACCES;
3414 goto out;
3415 }
3416 spin_unlock(&tcon->ses->server->srv_lock);
3417 } else
3418#endif /* CONFIG_CIFS_ALLOW_INSECURE_LEGACY */
3419 tcon->unix_ext = 0; /* server does not support them */
3420
3421 /* do not care if a following call succeed - informational */
3422 if (!tcon->pipe && server->ops->qfs_tcon) {
3423 server->ops->qfs_tcon(mnt_ctx->xid, tcon, cifs_sb);
3424 if (cifs_sb->mnt_cifs_flags & CIFS_MOUNT_RO_CACHE) {
3425 if (tcon->fsDevInfo.DeviceCharacteristics &
3426 cpu_to_le32(FILE_READ_ONLY_DEVICE))
3427 cifs_dbg(VFS, "mounted to read only share\n");
3428 else if ((cifs_sb->mnt_cifs_flags &
3429 CIFS_MOUNT_RW_CACHE) == 0)
3430 cifs_dbg(VFS, "read only mount of RW share\n");
3431 /* no need to log a RW mount of a typical RW share */
3432 }
3433 }
3434
3435 /*
3436 * Clamp the rsize/wsize mount arguments if they are too big for the server
3437 * and set the rsize/wsize to the negotiated values if not passed in by
3438 * the user on mount
3439 */
3440 if ((cifs_sb->ctx->wsize == 0) ||
3441 (cifs_sb->ctx->wsize > server->ops->negotiate_wsize(tcon, ctx)))
3442 cifs_sb->ctx->wsize = server->ops->negotiate_wsize(tcon, ctx);
3443 if ((cifs_sb->ctx->rsize == 0) ||
3444 (cifs_sb->ctx->rsize > server->ops->negotiate_rsize(tcon, ctx)))
3445 cifs_sb->ctx->rsize = server->ops->negotiate_rsize(tcon, ctx);
3446
3447 /*
3448 * The cookie is initialized from volume info returned above.
3449 * Inside cifs_fscache_get_super_cookie it checks
3450 * that we do not get super cookie twice.
3451 */
3452 if (cifs_sb->mnt_cifs_flags & CIFS_MOUNT_FSCACHE)
3453 cifs_fscache_get_super_cookie(tcon);
3454
3455out:
3456 mnt_ctx->tcon = tcon;
3457 return rc;
3458}
3459
3460static int mount_setup_tlink(struct cifs_sb_info *cifs_sb, struct cifs_ses *ses,
3461 struct cifs_tcon *tcon)
3462{
3463 struct tcon_link *tlink;
3464
3465 /* hang the tcon off of the superblock */
3466 tlink = kzalloc(sizeof(*tlink), GFP_KERNEL);
3467 if (tlink == NULL)
3468 return -ENOMEM;
3469
3470 tlink->tl_uid = ses->linux_uid;
3471 tlink->tl_tcon = tcon;
3472 tlink->tl_time = jiffies;
3473 set_bit(TCON_LINK_MASTER, &tlink->tl_flags);
3474 set_bit(TCON_LINK_IN_TREE, &tlink->tl_flags);
3475
3476 cifs_sb->master_tlink = tlink;
3477 spin_lock(&cifs_sb->tlink_tree_lock);
3478 tlink_rb_insert(&cifs_sb->tlink_tree, tlink);
3479 spin_unlock(&cifs_sb->tlink_tree_lock);
3480
3481 queue_delayed_work(cifsiod_wq, &cifs_sb->prune_tlinks,
3482 TLINK_IDLE_EXPIRE);
3483 return 0;
3484}
3485
3486static int
3487cifs_are_all_path_components_accessible(struct TCP_Server_Info *server,
3488 unsigned int xid,
3489 struct cifs_tcon *tcon,
3490 struct cifs_sb_info *cifs_sb,
3491 char *full_path,
3492 int added_treename)
3493{
3494 int rc;
3495 char *s;
3496 char sep, tmp;
3497 int skip = added_treename ? 1 : 0;
3498
3499 sep = CIFS_DIR_SEP(cifs_sb);
3500 s = full_path;
3501
3502 rc = server->ops->is_path_accessible(xid, tcon, cifs_sb, "");
3503 while (rc == 0) {
3504 /* skip separators */
3505 while (*s == sep)
3506 s++;
3507 if (!*s)
3508 break;
3509 /* next separator */
3510 while (*s && *s != sep)
3511 s++;
3512 /*
3513 * if the treename is added, we then have to skip the first
3514 * part within the separators
3515 */
3516 if (skip) {
3517 skip = 0;
3518 continue;
3519 }
3520 /*
3521 * temporarily null-terminate the path at the end of
3522 * the current component
3523 */
3524 tmp = *s;
3525 *s = 0;
3526 rc = server->ops->is_path_accessible(xid, tcon, cifs_sb,
3527 full_path);
3528 *s = tmp;
3529 }
3530 return rc;
3531}
3532
3533/*
3534 * Check if path is remote (i.e. a DFS share).
3535 *
3536 * Return -EREMOTE if it is, otherwise 0 or -errno.
3537 */
3538int cifs_is_path_remote(struct cifs_mount_ctx *mnt_ctx)
3539{
3540 int rc;
3541 struct cifs_sb_info *cifs_sb = mnt_ctx->cifs_sb;
3542 struct TCP_Server_Info *server = mnt_ctx->server;
3543 unsigned int xid = mnt_ctx->xid;
3544 struct cifs_tcon *tcon = mnt_ctx->tcon;
3545 struct smb3_fs_context *ctx = mnt_ctx->fs_ctx;
3546 char *full_path;
3547
3548 if (!server->ops->is_path_accessible)
3549 return -EOPNOTSUPP;
3550
3551 /*
3552 * cifs_build_path_to_root works only when we have a valid tcon
3553 */
3554 full_path = cifs_build_path_to_root(ctx, cifs_sb, tcon,
3555 tcon->Flags & SMB_SHARE_IS_IN_DFS);
3556 if (full_path == NULL)
3557 return -ENOMEM;
3558
3559 cifs_dbg(FYI, "%s: full_path: %s\n", __func__, full_path);
3560
3561 rc = server->ops->is_path_accessible(xid, tcon, cifs_sb,
3562 full_path);
3563 if (rc != 0 && rc != -EREMOTE)
3564 goto out;
3565
3566 if (rc != -EREMOTE) {
3567 rc = cifs_are_all_path_components_accessible(server, xid, tcon,
3568 cifs_sb, full_path, tcon->Flags & SMB_SHARE_IS_IN_DFS);
3569 if (rc != 0) {
3570 cifs_server_dbg(VFS, "cannot query dirs between root and final path, enabling CIFS_MOUNT_USE_PREFIX_PATH\n");
3571 cifs_sb->mnt_cifs_flags |= CIFS_MOUNT_USE_PREFIX_PATH;
3572 rc = 0;
3573 }
3574 }
3575
3576out:
3577 kfree(full_path);
3578 return rc;
3579}
3580
3581#ifdef CONFIG_CIFS_DFS_UPCALL
3582int cifs_mount(struct cifs_sb_info *cifs_sb, struct smb3_fs_context *ctx)
3583{
3584 struct cifs_mount_ctx mnt_ctx = { .cifs_sb = cifs_sb, .fs_ctx = ctx, };
3585 bool isdfs;
3586 int rc;
3587
3588 INIT_LIST_HEAD(&mnt_ctx.dfs_ses_list);
3589
3590 rc = dfs_mount_share(&mnt_ctx, &isdfs);
3591 if (rc)
3592 goto error;
3593 if (!isdfs)
3594 goto out;
3595
3596 /*
3597 * After reconnecting to a different server, unique ids won't match anymore, so we disable
3598 * serverino. This prevents dentry revalidation to think the dentry are stale (ESTALE).
3599 */
3600 cifs_autodisable_serverino(cifs_sb);
3601 /*
3602 * Force the use of prefix path to support failover on DFS paths that resolve to targets
3603 * that have different prefix paths.
3604 */
3605 cifs_sb->mnt_cifs_flags |= CIFS_MOUNT_USE_PREFIX_PATH;
3606 kfree(cifs_sb->prepath);
3607 cifs_sb->prepath = ctx->prepath;
3608 ctx->prepath = NULL;
3609
3610out:
3611 cifs_try_adding_channels(mnt_ctx.ses);
3612 rc = mount_setup_tlink(cifs_sb, mnt_ctx.ses, mnt_ctx.tcon);
3613 if (rc)
3614 goto error;
3615
3616 free_xid(mnt_ctx.xid);
3617 return rc;
3618
3619error:
3620 dfs_put_root_smb_sessions(&mnt_ctx.dfs_ses_list);
3621 cifs_mount_put_conns(&mnt_ctx);
3622 return rc;
3623}
3624#else
3625int cifs_mount(struct cifs_sb_info *cifs_sb, struct smb3_fs_context *ctx)
3626{
3627 int rc = 0;
3628 struct cifs_mount_ctx mnt_ctx = { .cifs_sb = cifs_sb, .fs_ctx = ctx, };
3629
3630 rc = cifs_mount_get_session(&mnt_ctx);
3631 if (rc)
3632 goto error;
3633
3634 rc = cifs_mount_get_tcon(&mnt_ctx);
3635 if (rc)
3636 goto error;
3637
3638 rc = cifs_is_path_remote(&mnt_ctx);
3639 if (rc == -EREMOTE)
3640 rc = -EOPNOTSUPP;
3641 if (rc)
3642 goto error;
3643
3644 rc = mount_setup_tlink(cifs_sb, mnt_ctx.ses, mnt_ctx.tcon);
3645 if (rc)
3646 goto error;
3647
3648 free_xid(mnt_ctx.xid);
3649 return rc;
3650
3651error:
3652 cifs_mount_put_conns(&mnt_ctx);
3653 return rc;
3654}
3655#endif
3656
3657/*
3658 * Issue a TREE_CONNECT request.
3659 */
3660int
3661CIFSTCon(const unsigned int xid, struct cifs_ses *ses,
3662 const char *tree, struct cifs_tcon *tcon,
3663 const struct nls_table *nls_codepage)
3664{
3665 struct smb_hdr *smb_buffer;
3666 struct smb_hdr *smb_buffer_response;
3667 TCONX_REQ *pSMB;
3668 TCONX_RSP *pSMBr;
3669 unsigned char *bcc_ptr;
3670 int rc = 0;
3671 int length;
3672 __u16 bytes_left, count;
3673
3674 if (ses == NULL)
3675 return -EIO;
3676
3677 smb_buffer = cifs_buf_get();
3678 if (smb_buffer == NULL)
3679 return -ENOMEM;
3680
3681 smb_buffer_response = smb_buffer;
3682
3683 header_assemble(smb_buffer, SMB_COM_TREE_CONNECT_ANDX,
3684 NULL /*no tid */, 4 /*wct */);
3685
3686 smb_buffer->Mid = get_next_mid(ses->server);
3687 smb_buffer->Uid = ses->Suid;
3688 pSMB = (TCONX_REQ *) smb_buffer;
3689 pSMBr = (TCONX_RSP *) smb_buffer_response;
3690
3691 pSMB->AndXCommand = 0xFF;
3692 pSMB->Flags = cpu_to_le16(TCON_EXTENDED_SECINFO);
3693 bcc_ptr = &pSMB->Password[0];
3694
3695 pSMB->PasswordLength = cpu_to_le16(1); /* minimum */
3696 *bcc_ptr = 0; /* password is null byte */
3697 bcc_ptr++; /* skip password */
3698 /* already aligned so no need to do it below */
3699
3700 if (ses->server->sign)
3701 smb_buffer->Flags2 |= SMBFLG2_SECURITY_SIGNATURE;
3702
3703 if (ses->capabilities & CAP_STATUS32)
3704 smb_buffer->Flags2 |= SMBFLG2_ERR_STATUS;
3705
3706 if (ses->capabilities & CAP_DFS)
3707 smb_buffer->Flags2 |= SMBFLG2_DFS;
3708
3709 if (ses->capabilities & CAP_UNICODE) {
3710 smb_buffer->Flags2 |= SMBFLG2_UNICODE;
3711 length =
3712 cifs_strtoUTF16((__le16 *) bcc_ptr, tree,
3713 6 /* max utf8 char length in bytes */ *
3714 (/* server len*/ + 256 /* share len */), nls_codepage);
3715 bcc_ptr += 2 * length; /* convert num 16 bit words to bytes */
3716 bcc_ptr += 2; /* skip trailing null */
3717 } else { /* ASCII */
3718 strcpy(bcc_ptr, tree);
3719 bcc_ptr += strlen(tree) + 1;
3720 }
3721 strcpy(bcc_ptr, "?????");
3722 bcc_ptr += strlen("?????");
3723 bcc_ptr += 1;
3724 count = bcc_ptr - &pSMB->Password[0];
3725 be32_add_cpu(&pSMB->hdr.smb_buf_length, count);
3726 pSMB->ByteCount = cpu_to_le16(count);
3727
3728 rc = SendReceive(xid, ses, smb_buffer, smb_buffer_response, &length,
3729 0);
3730
3731 /* above now done in SendReceive */
3732 if (rc == 0) {
3733 bool is_unicode;
3734
3735 tcon->tid = smb_buffer_response->Tid;
3736 bcc_ptr = pByteArea(smb_buffer_response);
3737 bytes_left = get_bcc(smb_buffer_response);
3738 length = strnlen(bcc_ptr, bytes_left - 2);
3739 if (smb_buffer->Flags2 & SMBFLG2_UNICODE)
3740 is_unicode = true;
3741 else
3742 is_unicode = false;
3743
3744
3745 /* skip service field (NB: this field is always ASCII) */
3746 if (length == 3) {
3747 if ((bcc_ptr[0] == 'I') && (bcc_ptr[1] == 'P') &&
3748 (bcc_ptr[2] == 'C')) {
3749 cifs_dbg(FYI, "IPC connection\n");
3750 tcon->ipc = true;
3751 tcon->pipe = true;
3752 }
3753 } else if (length == 2) {
3754 if ((bcc_ptr[0] == 'A') && (bcc_ptr[1] == ':')) {
3755 /* the most common case */
3756 cifs_dbg(FYI, "disk share connection\n");
3757 }
3758 }
3759 bcc_ptr += length + 1;
3760 bytes_left -= (length + 1);
3761 strscpy(tcon->tree_name, tree, sizeof(tcon->tree_name));
3762
3763 /* mostly informational -- no need to fail on error here */
3764 kfree(tcon->nativeFileSystem);
3765 tcon->nativeFileSystem = cifs_strndup_from_utf16(bcc_ptr,
3766 bytes_left, is_unicode,
3767 nls_codepage);
3768
3769 cifs_dbg(FYI, "nativeFileSystem=%s\n", tcon->nativeFileSystem);
3770
3771 if ((smb_buffer_response->WordCount == 3) ||
3772 (smb_buffer_response->WordCount == 7))
3773 /* field is in same location */
3774 tcon->Flags = le16_to_cpu(pSMBr->OptionalSupport);
3775 else
3776 tcon->Flags = 0;
3777 cifs_dbg(FYI, "Tcon flags: 0x%x\n", tcon->Flags);
3778 }
3779
3780 cifs_buf_release(smb_buffer);
3781 return rc;
3782}
3783
3784static void delayed_free(struct rcu_head *p)
3785{
3786 struct cifs_sb_info *cifs_sb = container_of(p, struct cifs_sb_info, rcu);
3787
3788 unload_nls(cifs_sb->local_nls);
3789 smb3_cleanup_fs_context(cifs_sb->ctx);
3790 kfree(cifs_sb);
3791}
3792
3793void
3794cifs_umount(struct cifs_sb_info *cifs_sb)
3795{
3796 struct rb_root *root = &cifs_sb->tlink_tree;
3797 struct rb_node *node;
3798 struct tcon_link *tlink;
3799
3800 cancel_delayed_work_sync(&cifs_sb->prune_tlinks);
3801
3802 spin_lock(&cifs_sb->tlink_tree_lock);
3803 while ((node = rb_first(root))) {
3804 tlink = rb_entry(node, struct tcon_link, tl_rbnode);
3805 cifs_get_tlink(tlink);
3806 clear_bit(TCON_LINK_IN_TREE, &tlink->tl_flags);
3807 rb_erase(node, root);
3808
3809 spin_unlock(&cifs_sb->tlink_tree_lock);
3810 cifs_put_tlink(tlink);
3811 spin_lock(&cifs_sb->tlink_tree_lock);
3812 }
3813 spin_unlock(&cifs_sb->tlink_tree_lock);
3814
3815 kfree(cifs_sb->prepath);
3816 call_rcu(&cifs_sb->rcu, delayed_free);
3817}
3818
3819int
3820cifs_negotiate_protocol(const unsigned int xid, struct cifs_ses *ses,
3821 struct TCP_Server_Info *server)
3822{
3823 int rc = 0;
3824
3825 if (!server->ops->need_neg || !server->ops->negotiate)
3826 return -ENOSYS;
3827
3828 /* only send once per connect */
3829 spin_lock(&server->srv_lock);
3830 if (server->tcpStatus != CifsGood &&
3831 server->tcpStatus != CifsNew &&
3832 server->tcpStatus != CifsNeedNegotiate) {
3833 spin_unlock(&server->srv_lock);
3834 return -EHOSTDOWN;
3835 }
3836
3837 if (!server->ops->need_neg(server) &&
3838 server->tcpStatus == CifsGood) {
3839 spin_unlock(&server->srv_lock);
3840 return 0;
3841 }
3842
3843 server->tcpStatus = CifsInNegotiate;
3844 spin_unlock(&server->srv_lock);
3845
3846 rc = server->ops->negotiate(xid, ses, server);
3847 if (rc == 0) {
3848 spin_lock(&server->srv_lock);
3849 if (server->tcpStatus == CifsInNegotiate)
3850 server->tcpStatus = CifsGood;
3851 else
3852 rc = -EHOSTDOWN;
3853 spin_unlock(&server->srv_lock);
3854 } else {
3855 spin_lock(&server->srv_lock);
3856 if (server->tcpStatus == CifsInNegotiate)
3857 server->tcpStatus = CifsNeedNegotiate;
3858 spin_unlock(&server->srv_lock);
3859 }
3860
3861 return rc;
3862}
3863
3864int
3865cifs_setup_session(const unsigned int xid, struct cifs_ses *ses,
3866 struct TCP_Server_Info *server,
3867 struct nls_table *nls_info)
3868{
3869 int rc = -ENOSYS;
3870 struct TCP_Server_Info *pserver = SERVER_IS_CHAN(server) ? server->primary_server : server;
3871 struct sockaddr_in6 *addr6 = (struct sockaddr_in6 *)&pserver->dstaddr;
3872 struct sockaddr_in *addr = (struct sockaddr_in *)&pserver->dstaddr;
3873 bool is_binding = false;
3874
3875 spin_lock(&ses->ses_lock);
3876 cifs_dbg(FYI, "%s: channel connect bitmap: 0x%lx\n",
3877 __func__, ses->chans_need_reconnect);
3878
3879 if (ses->ses_status != SES_GOOD &&
3880 ses->ses_status != SES_NEW &&
3881 ses->ses_status != SES_NEED_RECON) {
3882 spin_unlock(&ses->ses_lock);
3883 return -EHOSTDOWN;
3884 }
3885
3886 /* only send once per connect */
3887 spin_lock(&ses->chan_lock);
3888 if (CIFS_ALL_CHANS_GOOD(ses)) {
3889 if (ses->ses_status == SES_NEED_RECON)
3890 ses->ses_status = SES_GOOD;
3891 spin_unlock(&ses->chan_lock);
3892 spin_unlock(&ses->ses_lock);
3893 return 0;
3894 }
3895
3896 cifs_chan_set_in_reconnect(ses, server);
3897 is_binding = !CIFS_ALL_CHANS_NEED_RECONNECT(ses);
3898 spin_unlock(&ses->chan_lock);
3899
3900 if (!is_binding) {
3901 ses->ses_status = SES_IN_SETUP;
3902
3903 /* force iface_list refresh */
3904 ses->iface_last_update = 0;
3905 }
3906 spin_unlock(&ses->ses_lock);
3907
3908 /* update ses ip_addr only for primary chan */
3909 if (server == pserver) {
3910 if (server->dstaddr.ss_family == AF_INET6)
3911 scnprintf(ses->ip_addr, sizeof(ses->ip_addr), "%pI6", &addr6->sin6_addr);
3912 else
3913 scnprintf(ses->ip_addr, sizeof(ses->ip_addr), "%pI4", &addr->sin_addr);
3914 }
3915
3916 if (!is_binding) {
3917 ses->capabilities = server->capabilities;
3918 if (!linuxExtEnabled)
3919 ses->capabilities &= (~server->vals->cap_unix);
3920
3921 if (ses->auth_key.response) {
3922 cifs_dbg(FYI, "Free previous auth_key.response = %p\n",
3923 ses->auth_key.response);
3924 kfree_sensitive(ses->auth_key.response);
3925 ses->auth_key.response = NULL;
3926 ses->auth_key.len = 0;
3927 }
3928 }
3929
3930 cifs_dbg(FYI, "Security Mode: 0x%x Capabilities: 0x%x TimeAdjust: %d\n",
3931 server->sec_mode, server->capabilities, server->timeAdj);
3932
3933 if (server->ops->sess_setup)
3934 rc = server->ops->sess_setup(xid, ses, server, nls_info);
3935
3936 if (rc) {
3937 cifs_server_dbg(VFS, "Send error in SessSetup = %d\n", rc);
3938 spin_lock(&ses->ses_lock);
3939 if (ses->ses_status == SES_IN_SETUP)
3940 ses->ses_status = SES_NEED_RECON;
3941 spin_lock(&ses->chan_lock);
3942 cifs_chan_clear_in_reconnect(ses, server);
3943 spin_unlock(&ses->chan_lock);
3944 spin_unlock(&ses->ses_lock);
3945 } else {
3946 spin_lock(&ses->ses_lock);
3947 if (ses->ses_status == SES_IN_SETUP)
3948 ses->ses_status = SES_GOOD;
3949 spin_lock(&ses->chan_lock);
3950 cifs_chan_clear_in_reconnect(ses, server);
3951 cifs_chan_clear_need_reconnect(ses, server);
3952 spin_unlock(&ses->chan_lock);
3953 spin_unlock(&ses->ses_lock);
3954 }
3955
3956 return rc;
3957}
3958
3959static int
3960cifs_set_vol_auth(struct smb3_fs_context *ctx, struct cifs_ses *ses)
3961{
3962 ctx->sectype = ses->sectype;
3963
3964 /* krb5 is special, since we don't need username or pw */
3965 if (ctx->sectype == Kerberos)
3966 return 0;
3967
3968 return cifs_set_cifscreds(ctx, ses);
3969}
3970
3971static struct cifs_tcon *
3972cifs_construct_tcon(struct cifs_sb_info *cifs_sb, kuid_t fsuid)
3973{
3974 int rc;
3975 struct cifs_tcon *master_tcon = cifs_sb_master_tcon(cifs_sb);
3976 struct cifs_ses *ses;
3977 struct cifs_tcon *tcon = NULL;
3978 struct smb3_fs_context *ctx;
3979
3980 ctx = kzalloc(sizeof(*ctx), GFP_KERNEL);
3981 if (ctx == NULL)
3982 return ERR_PTR(-ENOMEM);
3983
3984 ctx->local_nls = cifs_sb->local_nls;
3985 ctx->linux_uid = fsuid;
3986 ctx->cred_uid = fsuid;
3987 ctx->UNC = master_tcon->tree_name;
3988 ctx->retry = master_tcon->retry;
3989 ctx->nocase = master_tcon->nocase;
3990 ctx->nohandlecache = master_tcon->nohandlecache;
3991 ctx->local_lease = master_tcon->local_lease;
3992 ctx->no_lease = master_tcon->no_lease;
3993 ctx->resilient = master_tcon->use_resilient;
3994 ctx->persistent = master_tcon->use_persistent;
3995 ctx->handle_timeout = master_tcon->handle_timeout;
3996 ctx->no_linux_ext = !master_tcon->unix_ext;
3997 ctx->linux_ext = master_tcon->posix_extensions;
3998 ctx->sectype = master_tcon->ses->sectype;
3999 ctx->sign = master_tcon->ses->sign;
4000 ctx->seal = master_tcon->seal;
4001 ctx->witness = master_tcon->use_witness;
4002
4003 rc = cifs_set_vol_auth(ctx, master_tcon->ses);
4004 if (rc) {
4005 tcon = ERR_PTR(rc);
4006 goto out;
4007 }
4008
4009 /* get a reference for the same TCP session */
4010 spin_lock(&cifs_tcp_ses_lock);
4011 ++master_tcon->ses->server->srv_count;
4012 spin_unlock(&cifs_tcp_ses_lock);
4013
4014 ses = cifs_get_smb_ses(master_tcon->ses->server, ctx);
4015 if (IS_ERR(ses)) {
4016 tcon = (struct cifs_tcon *)ses;
4017 cifs_put_tcp_session(master_tcon->ses->server, 0);
4018 goto out;
4019 }
4020
4021 tcon = cifs_get_tcon(ses, ctx);
4022 if (IS_ERR(tcon)) {
4023 cifs_put_smb_ses(ses);
4024 goto out;
4025 }
4026
4027#ifdef CONFIG_CIFS_ALLOW_INSECURE_LEGACY
4028 if (cap_unix(ses))
4029 reset_cifs_unix_caps(0, tcon, NULL, ctx);
4030#endif /* CONFIG_CIFS_ALLOW_INSECURE_LEGACY */
4031
4032out:
4033 kfree(ctx->username);
4034 kfree_sensitive(ctx->password);
4035 kfree(ctx);
4036
4037 return tcon;
4038}
4039
4040struct cifs_tcon *
4041cifs_sb_master_tcon(struct cifs_sb_info *cifs_sb)
4042{
4043 return tlink_tcon(cifs_sb_master_tlink(cifs_sb));
4044}
4045
4046/* find and return a tlink with given uid */
4047static struct tcon_link *
4048tlink_rb_search(struct rb_root *root, kuid_t uid)
4049{
4050 struct rb_node *node = root->rb_node;
4051 struct tcon_link *tlink;
4052
4053 while (node) {
4054 tlink = rb_entry(node, struct tcon_link, tl_rbnode);
4055
4056 if (uid_gt(tlink->tl_uid, uid))
4057 node = node->rb_left;
4058 else if (uid_lt(tlink->tl_uid, uid))
4059 node = node->rb_right;
4060 else
4061 return tlink;
4062 }
4063 return NULL;
4064}
4065
4066/* insert a tcon_link into the tree */
4067static void
4068tlink_rb_insert(struct rb_root *root, struct tcon_link *new_tlink)
4069{
4070 struct rb_node **new = &(root->rb_node), *parent = NULL;
4071 struct tcon_link *tlink;
4072
4073 while (*new) {
4074 tlink = rb_entry(*new, struct tcon_link, tl_rbnode);
4075 parent = *new;
4076
4077 if (uid_gt(tlink->tl_uid, new_tlink->tl_uid))
4078 new = &((*new)->rb_left);
4079 else
4080 new = &((*new)->rb_right);
4081 }
4082
4083 rb_link_node(&new_tlink->tl_rbnode, parent, new);
4084 rb_insert_color(&new_tlink->tl_rbnode, root);
4085}
4086
4087/*
4088 * Find or construct an appropriate tcon given a cifs_sb and the fsuid of the
4089 * current task.
4090 *
4091 * If the superblock doesn't refer to a multiuser mount, then just return
4092 * the master tcon for the mount.
4093 *
4094 * First, search the rbtree for an existing tcon for this fsuid. If one
4095 * exists, then check to see if it's pending construction. If it is then wait
4096 * for construction to complete. Once it's no longer pending, check to see if
4097 * it failed and either return an error or retry construction, depending on
4098 * the timeout.
4099 *
4100 * If one doesn't exist then insert a new tcon_link struct into the tree and
4101 * try to construct a new one.
4102 */
4103struct tcon_link *
4104cifs_sb_tlink(struct cifs_sb_info *cifs_sb)
4105{
4106 int ret;
4107 kuid_t fsuid = current_fsuid();
4108 struct tcon_link *tlink, *newtlink;
4109
4110 if (!(cifs_sb->mnt_cifs_flags & CIFS_MOUNT_MULTIUSER))
4111 return cifs_get_tlink(cifs_sb_master_tlink(cifs_sb));
4112
4113 spin_lock(&cifs_sb->tlink_tree_lock);
4114 tlink = tlink_rb_search(&cifs_sb->tlink_tree, fsuid);
4115 if (tlink)
4116 cifs_get_tlink(tlink);
4117 spin_unlock(&cifs_sb->tlink_tree_lock);
4118
4119 if (tlink == NULL) {
4120 newtlink = kzalloc(sizeof(*tlink), GFP_KERNEL);
4121 if (newtlink == NULL)
4122 return ERR_PTR(-ENOMEM);
4123 newtlink->tl_uid = fsuid;
4124 newtlink->tl_tcon = ERR_PTR(-EACCES);
4125 set_bit(TCON_LINK_PENDING, &newtlink->tl_flags);
4126 set_bit(TCON_LINK_IN_TREE, &newtlink->tl_flags);
4127 cifs_get_tlink(newtlink);
4128
4129 spin_lock(&cifs_sb->tlink_tree_lock);
4130 /* was one inserted after previous search? */
4131 tlink = tlink_rb_search(&cifs_sb->tlink_tree, fsuid);
4132 if (tlink) {
4133 cifs_get_tlink(tlink);
4134 spin_unlock(&cifs_sb->tlink_tree_lock);
4135 kfree(newtlink);
4136 goto wait_for_construction;
4137 }
4138 tlink = newtlink;
4139 tlink_rb_insert(&cifs_sb->tlink_tree, tlink);
4140 spin_unlock(&cifs_sb->tlink_tree_lock);
4141 } else {
4142wait_for_construction:
4143 ret = wait_on_bit(&tlink->tl_flags, TCON_LINK_PENDING,
4144 TASK_INTERRUPTIBLE);
4145 if (ret) {
4146 cifs_put_tlink(tlink);
4147 return ERR_PTR(-ERESTARTSYS);
4148 }
4149
4150 /* if it's good, return it */
4151 if (!IS_ERR(tlink->tl_tcon))
4152 return tlink;
4153
4154 /* return error if we tried this already recently */
4155 if (time_before(jiffies, tlink->tl_time + TLINK_ERROR_EXPIRE)) {
4156 cifs_put_tlink(tlink);
4157 return ERR_PTR(-EACCES);
4158 }
4159
4160 if (test_and_set_bit(TCON_LINK_PENDING, &tlink->tl_flags))
4161 goto wait_for_construction;
4162 }
4163
4164 tlink->tl_tcon = cifs_construct_tcon(cifs_sb, fsuid);
4165 clear_bit(TCON_LINK_PENDING, &tlink->tl_flags);
4166 wake_up_bit(&tlink->tl_flags, TCON_LINK_PENDING);
4167
4168 if (IS_ERR(tlink->tl_tcon)) {
4169 cifs_put_tlink(tlink);
4170 return ERR_PTR(-EACCES);
4171 }
4172
4173 return tlink;
4174}
4175
4176/*
4177 * periodic workqueue job that scans tcon_tree for a superblock and closes
4178 * out tcons.
4179 */
4180static void
4181cifs_prune_tlinks(struct work_struct *work)
4182{
4183 struct cifs_sb_info *cifs_sb = container_of(work, struct cifs_sb_info,
4184 prune_tlinks.work);
4185 struct rb_root *root = &cifs_sb->tlink_tree;
4186 struct rb_node *node;
4187 struct rb_node *tmp;
4188 struct tcon_link *tlink;
4189
4190 /*
4191 * Because we drop the spinlock in the loop in order to put the tlink
4192 * it's not guarded against removal of links from the tree. The only
4193 * places that remove entries from the tree are this function and
4194 * umounts. Because this function is non-reentrant and is canceled
4195 * before umount can proceed, this is safe.
4196 */
4197 spin_lock(&cifs_sb->tlink_tree_lock);
4198 node = rb_first(root);
4199 while (node != NULL) {
4200 tmp = node;
4201 node = rb_next(tmp);
4202 tlink = rb_entry(tmp, struct tcon_link, tl_rbnode);
4203
4204 if (test_bit(TCON_LINK_MASTER, &tlink->tl_flags) ||
4205 atomic_read(&tlink->tl_count) != 0 ||
4206 time_after(tlink->tl_time + TLINK_IDLE_EXPIRE, jiffies))
4207 continue;
4208
4209 cifs_get_tlink(tlink);
4210 clear_bit(TCON_LINK_IN_TREE, &tlink->tl_flags);
4211 rb_erase(tmp, root);
4212
4213 spin_unlock(&cifs_sb->tlink_tree_lock);
4214 cifs_put_tlink(tlink);
4215 spin_lock(&cifs_sb->tlink_tree_lock);
4216 }
4217 spin_unlock(&cifs_sb->tlink_tree_lock);
4218
4219 queue_delayed_work(cifsiod_wq, &cifs_sb->prune_tlinks,
4220 TLINK_IDLE_EXPIRE);
4221}
4222
4223#ifndef CONFIG_CIFS_DFS_UPCALL
4224int cifs_tree_connect(const unsigned int xid, struct cifs_tcon *tcon, const struct nls_table *nlsc)
4225{
4226 int rc;
4227 const struct smb_version_operations *ops = tcon->ses->server->ops;
4228
4229 /* only send once per connect */
4230 spin_lock(&tcon->tc_lock);
4231 if (tcon->status == TID_GOOD) {
4232 spin_unlock(&tcon->tc_lock);
4233 return 0;
4234 }
4235
4236 if (tcon->status != TID_NEW &&
4237 tcon->status != TID_NEED_TCON) {
4238 spin_unlock(&tcon->tc_lock);
4239 return -EHOSTDOWN;
4240 }
4241
4242 tcon->status = TID_IN_TCON;
4243 spin_unlock(&tcon->tc_lock);
4244
4245 rc = ops->tree_connect(xid, tcon->ses, tcon->tree_name, tcon, nlsc);
4246 if (rc) {
4247 spin_lock(&tcon->tc_lock);
4248 if (tcon->status == TID_IN_TCON)
4249 tcon->status = TID_NEED_TCON;
4250 spin_unlock(&tcon->tc_lock);
4251 } else {
4252 spin_lock(&tcon->tc_lock);
4253 if (tcon->status == TID_IN_TCON)
4254 tcon->status = TID_GOOD;
4255 tcon->need_reconnect = false;
4256 spin_unlock(&tcon->tc_lock);
4257 }
4258
4259 return rc;
4260}
4261#endif