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