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