smb: move client and server files to common directory fs/smb
[platform/kernel/linux-starfive.git] / fs / smb / client / misc.c
1 // SPDX-License-Identifier: LGPL-2.1
2 /*
3  *
4  *   Copyright (C) International Business Machines  Corp., 2002,2008
5  *   Author(s): Steve French (sfrench@us.ibm.com)
6  *
7  */
8
9 #include <linux/slab.h>
10 #include <linux/ctype.h>
11 #include <linux/mempool.h>
12 #include <linux/vmalloc.h>
13 #include "cifspdu.h"
14 #include "cifsglob.h"
15 #include "cifsproto.h"
16 #include "cifs_debug.h"
17 #include "smberr.h"
18 #include "nterr.h"
19 #include "cifs_unicode.h"
20 #include "smb2pdu.h"
21 #include "cifsfs.h"
22 #ifdef CONFIG_CIFS_DFS_UPCALL
23 #include "dns_resolve.h"
24 #include "dfs_cache.h"
25 #endif
26 #include "fs_context.h"
27 #include "cached_dir.h"
28
29 extern mempool_t *cifs_sm_req_poolp;
30 extern mempool_t *cifs_req_poolp;
31
32 /* The xid serves as a useful identifier for each incoming vfs request,
33    in a similar way to the mid which is useful to track each sent smb,
34    and CurrentXid can also provide a running counter (although it
35    will eventually wrap past zero) of the total vfs operations handled
36    since the cifs fs was mounted */
37
38 unsigned int
39 _get_xid(void)
40 {
41         unsigned int xid;
42
43         spin_lock(&GlobalMid_Lock);
44         GlobalTotalActiveXid++;
45
46         /* keep high water mark for number of simultaneous ops in filesystem */
47         if (GlobalTotalActiveXid > GlobalMaxActiveXid)
48                 GlobalMaxActiveXid = GlobalTotalActiveXid;
49         if (GlobalTotalActiveXid > 65000)
50                 cifs_dbg(FYI, "warning: more than 65000 requests active\n");
51         xid = GlobalCurrentXid++;
52         spin_unlock(&GlobalMid_Lock);
53         return xid;
54 }
55
56 void
57 _free_xid(unsigned int xid)
58 {
59         spin_lock(&GlobalMid_Lock);
60         /* if (GlobalTotalActiveXid == 0)
61                 BUG(); */
62         GlobalTotalActiveXid--;
63         spin_unlock(&GlobalMid_Lock);
64 }
65
66 struct cifs_ses *
67 sesInfoAlloc(void)
68 {
69         struct cifs_ses *ret_buf;
70
71         ret_buf = kzalloc(sizeof(struct cifs_ses), GFP_KERNEL);
72         if (ret_buf) {
73                 atomic_inc(&sesInfoAllocCount);
74                 spin_lock_init(&ret_buf->ses_lock);
75                 ret_buf->ses_status = SES_NEW;
76                 ++ret_buf->ses_count;
77                 INIT_LIST_HEAD(&ret_buf->smb_ses_list);
78                 INIT_LIST_HEAD(&ret_buf->tcon_list);
79                 mutex_init(&ret_buf->session_mutex);
80                 spin_lock_init(&ret_buf->iface_lock);
81                 INIT_LIST_HEAD(&ret_buf->iface_list);
82                 spin_lock_init(&ret_buf->chan_lock);
83         }
84         return ret_buf;
85 }
86
87 void
88 sesInfoFree(struct cifs_ses *buf_to_free)
89 {
90         struct cifs_server_iface *iface = NULL, *niface = NULL;
91
92         if (buf_to_free == NULL) {
93                 cifs_dbg(FYI, "Null buffer passed to sesInfoFree\n");
94                 return;
95         }
96
97         atomic_dec(&sesInfoAllocCount);
98         kfree(buf_to_free->serverOS);
99         kfree(buf_to_free->serverDomain);
100         kfree(buf_to_free->serverNOS);
101         kfree_sensitive(buf_to_free->password);
102         kfree(buf_to_free->user_name);
103         kfree(buf_to_free->domainName);
104         kfree_sensitive(buf_to_free->auth_key.response);
105         spin_lock(&buf_to_free->iface_lock);
106         list_for_each_entry_safe(iface, niface, &buf_to_free->iface_list,
107                                  iface_head)
108                 kref_put(&iface->refcount, release_iface);
109         spin_unlock(&buf_to_free->iface_lock);
110         kfree_sensitive(buf_to_free);
111 }
112
113 struct cifs_tcon *
114 tconInfoAlloc(void)
115 {
116         struct cifs_tcon *ret_buf;
117
118         ret_buf = kzalloc(sizeof(*ret_buf), GFP_KERNEL);
119         if (!ret_buf)
120                 return NULL;
121         ret_buf->cfids = init_cached_dirs();
122         if (!ret_buf->cfids) {
123                 kfree(ret_buf);
124                 return NULL;
125         }
126
127         atomic_inc(&tconInfoAllocCount);
128         ret_buf->status = TID_NEW;
129         ++ret_buf->tc_count;
130         spin_lock_init(&ret_buf->tc_lock);
131         INIT_LIST_HEAD(&ret_buf->openFileList);
132         INIT_LIST_HEAD(&ret_buf->tcon_list);
133         spin_lock_init(&ret_buf->open_file_lock);
134         spin_lock_init(&ret_buf->stat_lock);
135         atomic_set(&ret_buf->num_local_opens, 0);
136         atomic_set(&ret_buf->num_remote_opens, 0);
137
138         return ret_buf;
139 }
140
141 void
142 tconInfoFree(struct cifs_tcon *tcon)
143 {
144         if (tcon == NULL) {
145                 cifs_dbg(FYI, "Null buffer passed to tconInfoFree\n");
146                 return;
147         }
148         free_cached_dirs(tcon->cfids);
149         atomic_dec(&tconInfoAllocCount);
150         kfree(tcon->nativeFileSystem);
151         kfree_sensitive(tcon->password);
152         kfree(tcon);
153 }
154
155 struct smb_hdr *
156 cifs_buf_get(void)
157 {
158         struct smb_hdr *ret_buf = NULL;
159         /*
160          * SMB2 header is bigger than CIFS one - no problems to clean some
161          * more bytes for CIFS.
162          */
163         size_t buf_size = sizeof(struct smb2_hdr);
164
165         /*
166          * We could use negotiated size instead of max_msgsize -
167          * but it may be more efficient to always alloc same size
168          * albeit slightly larger than necessary and maxbuffersize
169          * defaults to this and can not be bigger.
170          */
171         ret_buf = mempool_alloc(cifs_req_poolp, GFP_NOFS);
172
173         /* clear the first few header bytes */
174         /* for most paths, more is cleared in header_assemble */
175         memset(ret_buf, 0, buf_size + 3);
176         atomic_inc(&buf_alloc_count);
177 #ifdef CONFIG_CIFS_STATS2
178         atomic_inc(&total_buf_alloc_count);
179 #endif /* CONFIG_CIFS_STATS2 */
180
181         return ret_buf;
182 }
183
184 void
185 cifs_buf_release(void *buf_to_free)
186 {
187         if (buf_to_free == NULL) {
188                 /* cifs_dbg(FYI, "Null buffer passed to cifs_buf_release\n");*/
189                 return;
190         }
191         mempool_free(buf_to_free, cifs_req_poolp);
192
193         atomic_dec(&buf_alloc_count);
194         return;
195 }
196
197 struct smb_hdr *
198 cifs_small_buf_get(void)
199 {
200         struct smb_hdr *ret_buf = NULL;
201
202 /* We could use negotiated size instead of max_msgsize -
203    but it may be more efficient to always alloc same size
204    albeit slightly larger than necessary and maxbuffersize
205    defaults to this and can not be bigger */
206         ret_buf = mempool_alloc(cifs_sm_req_poolp, GFP_NOFS);
207         /* No need to clear memory here, cleared in header assemble */
208         /*      memset(ret_buf, 0, sizeof(struct smb_hdr) + 27);*/
209         atomic_inc(&small_buf_alloc_count);
210 #ifdef CONFIG_CIFS_STATS2
211         atomic_inc(&total_small_buf_alloc_count);
212 #endif /* CONFIG_CIFS_STATS2 */
213
214         return ret_buf;
215 }
216
217 void
218 cifs_small_buf_release(void *buf_to_free)
219 {
220
221         if (buf_to_free == NULL) {
222                 cifs_dbg(FYI, "Null buffer passed to cifs_small_buf_release\n");
223                 return;
224         }
225         mempool_free(buf_to_free, cifs_sm_req_poolp);
226
227         atomic_dec(&small_buf_alloc_count);
228         return;
229 }
230
231 void
232 free_rsp_buf(int resp_buftype, void *rsp)
233 {
234         if (resp_buftype == CIFS_SMALL_BUFFER)
235                 cifs_small_buf_release(rsp);
236         else if (resp_buftype == CIFS_LARGE_BUFFER)
237                 cifs_buf_release(rsp);
238 }
239
240 /* NB: MID can not be set if treeCon not passed in, in that
241    case it is responsbility of caller to set the mid */
242 void
243 header_assemble(struct smb_hdr *buffer, char smb_command /* command */ ,
244                 const struct cifs_tcon *treeCon, int word_count
245                 /* length of fixed section (word count) in two byte units  */)
246 {
247         char *temp = (char *) buffer;
248
249         memset(temp, 0, 256); /* bigger than MAX_CIFS_HDR_SIZE */
250
251         buffer->smb_buf_length = cpu_to_be32(
252             (2 * word_count) + sizeof(struct smb_hdr) -
253             4 /*  RFC 1001 length field does not count */  +
254             2 /* for bcc field itself */) ;
255
256         buffer->Protocol[0] = 0xFF;
257         buffer->Protocol[1] = 'S';
258         buffer->Protocol[2] = 'M';
259         buffer->Protocol[3] = 'B';
260         buffer->Command = smb_command;
261         buffer->Flags = 0x00;   /* case sensitive */
262         buffer->Flags2 = SMBFLG2_KNOWS_LONG_NAMES;
263         buffer->Pid = cpu_to_le16((__u16)current->tgid);
264         buffer->PidHigh = cpu_to_le16((__u16)(current->tgid >> 16));
265         if (treeCon) {
266                 buffer->Tid = treeCon->tid;
267                 if (treeCon->ses) {
268                         if (treeCon->ses->capabilities & CAP_UNICODE)
269                                 buffer->Flags2 |= SMBFLG2_UNICODE;
270                         if (treeCon->ses->capabilities & CAP_STATUS32)
271                                 buffer->Flags2 |= SMBFLG2_ERR_STATUS;
272
273                         /* Uid is not converted */
274                         buffer->Uid = treeCon->ses->Suid;
275                         if (treeCon->ses->server)
276                                 buffer->Mid = get_next_mid(treeCon->ses->server);
277                 }
278                 if (treeCon->Flags & SMB_SHARE_IS_IN_DFS)
279                         buffer->Flags2 |= SMBFLG2_DFS;
280                 if (treeCon->nocase)
281                         buffer->Flags  |= SMBFLG_CASELESS;
282                 if ((treeCon->ses) && (treeCon->ses->server))
283                         if (treeCon->ses->server->sign)
284                                 buffer->Flags2 |= SMBFLG2_SECURITY_SIGNATURE;
285         }
286
287 /*  endian conversion of flags is now done just before sending */
288         buffer->WordCount = (char) word_count;
289         return;
290 }
291
292 static int
293 check_smb_hdr(struct smb_hdr *smb)
294 {
295         /* does it have the right SMB "signature" ? */
296         if (*(__le32 *) smb->Protocol != cpu_to_le32(0x424d53ff)) {
297                 cifs_dbg(VFS, "Bad protocol string signature header 0x%x\n",
298                          *(unsigned int *)smb->Protocol);
299                 return 1;
300         }
301
302         /* if it's a response then accept */
303         if (smb->Flags & SMBFLG_RESPONSE)
304                 return 0;
305
306         /* only one valid case where server sends us request */
307         if (smb->Command == SMB_COM_LOCKING_ANDX)
308                 return 0;
309
310         cifs_dbg(VFS, "Server sent request, not response. mid=%u\n",
311                  get_mid(smb));
312         return 1;
313 }
314
315 int
316 checkSMB(char *buf, unsigned int total_read, struct TCP_Server_Info *server)
317 {
318         struct smb_hdr *smb = (struct smb_hdr *)buf;
319         __u32 rfclen = be32_to_cpu(smb->smb_buf_length);
320         __u32 clc_len;  /* calculated length */
321         cifs_dbg(FYI, "checkSMB Length: 0x%x, smb_buf_length: 0x%x\n",
322                  total_read, rfclen);
323
324         /* is this frame too small to even get to a BCC? */
325         if (total_read < 2 + sizeof(struct smb_hdr)) {
326                 if ((total_read >= sizeof(struct smb_hdr) - 1)
327                             && (smb->Status.CifsError != 0)) {
328                         /* it's an error return */
329                         smb->WordCount = 0;
330                         /* some error cases do not return wct and bcc */
331                         return 0;
332                 } else if ((total_read == sizeof(struct smb_hdr) + 1) &&
333                                 (smb->WordCount == 0)) {
334                         char *tmp = (char *)smb;
335                         /* Need to work around a bug in two servers here */
336                         /* First, check if the part of bcc they sent was zero */
337                         if (tmp[sizeof(struct smb_hdr)] == 0) {
338                                 /* some servers return only half of bcc
339                                  * on simple responses (wct, bcc both zero)
340                                  * in particular have seen this on
341                                  * ulogoffX and FindClose. This leaves
342                                  * one byte of bcc potentially unitialized
343                                  */
344                                 /* zero rest of bcc */
345                                 tmp[sizeof(struct smb_hdr)+1] = 0;
346                                 return 0;
347                         }
348                         cifs_dbg(VFS, "rcvd invalid byte count (bcc)\n");
349                 } else {
350                         cifs_dbg(VFS, "Length less than smb header size\n");
351                 }
352                 return -EIO;
353         }
354
355         /* otherwise, there is enough to get to the BCC */
356         if (check_smb_hdr(smb))
357                 return -EIO;
358         clc_len = smbCalcSize(smb);
359
360         if (4 + rfclen != total_read) {
361                 cifs_dbg(VFS, "Length read does not match RFC1001 length %d\n",
362                          rfclen);
363                 return -EIO;
364         }
365
366         if (4 + rfclen != clc_len) {
367                 __u16 mid = get_mid(smb);
368                 /* check if bcc wrapped around for large read responses */
369                 if ((rfclen > 64 * 1024) && (rfclen > clc_len)) {
370                         /* check if lengths match mod 64K */
371                         if (((4 + rfclen) & 0xFFFF) == (clc_len & 0xFFFF))
372                                 return 0; /* bcc wrapped */
373                 }
374                 cifs_dbg(FYI, "Calculated size %u vs length %u mismatch for mid=%u\n",
375                          clc_len, 4 + rfclen, mid);
376
377                 if (4 + rfclen < clc_len) {
378                         cifs_dbg(VFS, "RFC1001 size %u smaller than SMB for mid=%u\n",
379                                  rfclen, mid);
380                         return -EIO;
381                 } else if (rfclen > clc_len + 512) {
382                         /*
383                          * Some servers (Windows XP in particular) send more
384                          * data than the lengths in the SMB packet would
385                          * indicate on certain calls (byte range locks and
386                          * trans2 find first calls in particular). While the
387                          * client can handle such a frame by ignoring the
388                          * trailing data, we choose limit the amount of extra
389                          * data to 512 bytes.
390                          */
391                         cifs_dbg(VFS, "RFC1001 size %u more than 512 bytes larger than SMB for mid=%u\n",
392                                  rfclen, mid);
393                         return -EIO;
394                 }
395         }
396         return 0;
397 }
398
399 bool
400 is_valid_oplock_break(char *buffer, struct TCP_Server_Info *srv)
401 {
402         struct smb_hdr *buf = (struct smb_hdr *)buffer;
403         struct smb_com_lock_req *pSMB = (struct smb_com_lock_req *)buf;
404         struct TCP_Server_Info *pserver;
405         struct cifs_ses *ses;
406         struct cifs_tcon *tcon;
407         struct cifsInodeInfo *pCifsInode;
408         struct cifsFileInfo *netfile;
409
410         cifs_dbg(FYI, "Checking for oplock break or dnotify response\n");
411         if ((pSMB->hdr.Command == SMB_COM_NT_TRANSACT) &&
412            (pSMB->hdr.Flags & SMBFLG_RESPONSE)) {
413                 struct smb_com_transaction_change_notify_rsp *pSMBr =
414                         (struct smb_com_transaction_change_notify_rsp *)buf;
415                 struct file_notify_information *pnotify;
416                 __u32 data_offset = 0;
417                 size_t len = srv->total_read - sizeof(pSMBr->hdr.smb_buf_length);
418
419                 if (get_bcc(buf) > sizeof(struct file_notify_information)) {
420                         data_offset = le32_to_cpu(pSMBr->DataOffset);
421
422                         if (data_offset >
423                             len - sizeof(struct file_notify_information)) {
424                                 cifs_dbg(FYI, "Invalid data_offset %u\n",
425                                          data_offset);
426                                 return true;
427                         }
428                         pnotify = (struct file_notify_information *)
429                                 ((char *)&pSMBr->hdr.Protocol + data_offset);
430                         cifs_dbg(FYI, "dnotify on %s Action: 0x%x\n",
431                                  pnotify->FileName, pnotify->Action);
432                         /*   cifs_dump_mem("Rcvd notify Data: ",buf,
433                                 sizeof(struct smb_hdr)+60); */
434                         return true;
435                 }
436                 if (pSMBr->hdr.Status.CifsError) {
437                         cifs_dbg(FYI, "notify err 0x%x\n",
438                                  pSMBr->hdr.Status.CifsError);
439                         return true;
440                 }
441                 return false;
442         }
443         if (pSMB->hdr.Command != SMB_COM_LOCKING_ANDX)
444                 return false;
445         if (pSMB->hdr.Flags & SMBFLG_RESPONSE) {
446                 /* no sense logging error on invalid handle on oplock
447                    break - harmless race between close request and oplock
448                    break response is expected from time to time writing out
449                    large dirty files cached on the client */
450                 if ((NT_STATUS_INVALID_HANDLE) ==
451                    le32_to_cpu(pSMB->hdr.Status.CifsError)) {
452                         cifs_dbg(FYI, "Invalid handle on oplock break\n");
453                         return true;
454                 } else if (ERRbadfid ==
455                    le16_to_cpu(pSMB->hdr.Status.DosError.Error)) {
456                         return true;
457                 } else {
458                         return false; /* on valid oplock brk we get "request" */
459                 }
460         }
461         if (pSMB->hdr.WordCount != 8)
462                 return false;
463
464         cifs_dbg(FYI, "oplock type 0x%x level 0x%x\n",
465                  pSMB->LockType, pSMB->OplockLevel);
466         if (!(pSMB->LockType & LOCKING_ANDX_OPLOCK_RELEASE))
467                 return false;
468
469         /* If server is a channel, select the primary channel */
470         pserver = CIFS_SERVER_IS_CHAN(srv) ? srv->primary_server : srv;
471
472         /* look up tcon based on tid & uid */
473         spin_lock(&cifs_tcp_ses_lock);
474         list_for_each_entry(ses, &pserver->smb_ses_list, smb_ses_list) {
475                 list_for_each_entry(tcon, &ses->tcon_list, tcon_list) {
476                         if (tcon->tid != buf->Tid)
477                                 continue;
478
479                         cifs_stats_inc(&tcon->stats.cifs_stats.num_oplock_brks);
480                         spin_lock(&tcon->open_file_lock);
481                         list_for_each_entry(netfile, &tcon->openFileList, tlist) {
482                                 if (pSMB->Fid != netfile->fid.netfid)
483                                         continue;
484
485                                 cifs_dbg(FYI, "file id match, oplock break\n");
486                                 pCifsInode = CIFS_I(d_inode(netfile->dentry));
487
488                                 set_bit(CIFS_INODE_PENDING_OPLOCK_BREAK,
489                                         &pCifsInode->flags);
490
491                                 netfile->oplock_epoch = 0;
492                                 netfile->oplock_level = pSMB->OplockLevel;
493                                 netfile->oplock_break_cancelled = false;
494                                 cifs_queue_oplock_break(netfile);
495
496                                 spin_unlock(&tcon->open_file_lock);
497                                 spin_unlock(&cifs_tcp_ses_lock);
498                                 return true;
499                         }
500                         spin_unlock(&tcon->open_file_lock);
501                         spin_unlock(&cifs_tcp_ses_lock);
502                         cifs_dbg(FYI, "No matching file for oplock break\n");
503                         return true;
504                 }
505         }
506         spin_unlock(&cifs_tcp_ses_lock);
507         cifs_dbg(FYI, "Can not process oplock break for non-existent connection\n");
508         return true;
509 }
510
511 void
512 dump_smb(void *buf, int smb_buf_length)
513 {
514         if (traceSMB == 0)
515                 return;
516
517         print_hex_dump(KERN_DEBUG, "", DUMP_PREFIX_NONE, 8, 2, buf,
518                        smb_buf_length, true);
519 }
520
521 void
522 cifs_autodisable_serverino(struct cifs_sb_info *cifs_sb)
523 {
524         if (cifs_sb->mnt_cifs_flags & CIFS_MOUNT_SERVER_INUM) {
525                 struct cifs_tcon *tcon = NULL;
526
527                 if (cifs_sb->master_tlink)
528                         tcon = cifs_sb_master_tcon(cifs_sb);
529
530                 cifs_sb->mnt_cifs_flags &= ~CIFS_MOUNT_SERVER_INUM;
531                 cifs_sb->mnt_cifs_serverino_autodisabled = true;
532                 cifs_dbg(VFS, "Autodisabling the use of server inode numbers on %s\n",
533                          tcon ? tcon->tree_name : "new server");
534                 cifs_dbg(VFS, "The server doesn't seem to support them properly or the files might be on different servers (DFS)\n");
535                 cifs_dbg(VFS, "Hardlinks will not be recognized on this mount. Consider mounting with the \"noserverino\" option to silence this message.\n");
536
537         }
538 }
539
540 void cifs_set_oplock_level(struct cifsInodeInfo *cinode, __u32 oplock)
541 {
542         oplock &= 0xF;
543
544         if (oplock == OPLOCK_EXCLUSIVE) {
545                 cinode->oplock = CIFS_CACHE_WRITE_FLG | CIFS_CACHE_READ_FLG;
546                 cifs_dbg(FYI, "Exclusive Oplock granted on inode %p\n",
547                          &cinode->netfs.inode);
548         } else if (oplock == OPLOCK_READ) {
549                 cinode->oplock = CIFS_CACHE_READ_FLG;
550                 cifs_dbg(FYI, "Level II Oplock granted on inode %p\n",
551                          &cinode->netfs.inode);
552         } else
553                 cinode->oplock = 0;
554 }
555
556 /*
557  * We wait for oplock breaks to be processed before we attempt to perform
558  * writes.
559  */
560 int cifs_get_writer(struct cifsInodeInfo *cinode)
561 {
562         int rc;
563
564 start:
565         rc = wait_on_bit(&cinode->flags, CIFS_INODE_PENDING_OPLOCK_BREAK,
566                          TASK_KILLABLE);
567         if (rc)
568                 return rc;
569
570         spin_lock(&cinode->writers_lock);
571         if (!cinode->writers)
572                 set_bit(CIFS_INODE_PENDING_WRITERS, &cinode->flags);
573         cinode->writers++;
574         /* Check to see if we have started servicing an oplock break */
575         if (test_bit(CIFS_INODE_PENDING_OPLOCK_BREAK, &cinode->flags)) {
576                 cinode->writers--;
577                 if (cinode->writers == 0) {
578                         clear_bit(CIFS_INODE_PENDING_WRITERS, &cinode->flags);
579                         wake_up_bit(&cinode->flags, CIFS_INODE_PENDING_WRITERS);
580                 }
581                 spin_unlock(&cinode->writers_lock);
582                 goto start;
583         }
584         spin_unlock(&cinode->writers_lock);
585         return 0;
586 }
587
588 void cifs_put_writer(struct cifsInodeInfo *cinode)
589 {
590         spin_lock(&cinode->writers_lock);
591         cinode->writers--;
592         if (cinode->writers == 0) {
593                 clear_bit(CIFS_INODE_PENDING_WRITERS, &cinode->flags);
594                 wake_up_bit(&cinode->flags, CIFS_INODE_PENDING_WRITERS);
595         }
596         spin_unlock(&cinode->writers_lock);
597 }
598
599 /**
600  * cifs_queue_oplock_break - queue the oplock break handler for cfile
601  * @cfile: The file to break the oplock on
602  *
603  * This function is called from the demultiplex thread when it
604  * receives an oplock break for @cfile.
605  *
606  * Assumes the tcon->open_file_lock is held.
607  * Assumes cfile->file_info_lock is NOT held.
608  */
609 void cifs_queue_oplock_break(struct cifsFileInfo *cfile)
610 {
611         /*
612          * Bump the handle refcount now while we hold the
613          * open_file_lock to enforce the validity of it for the oplock
614          * break handler. The matching put is done at the end of the
615          * handler.
616          */
617         cifsFileInfo_get(cfile);
618
619         queue_work(cifsoplockd_wq, &cfile->oplock_break);
620 }
621
622 void cifs_done_oplock_break(struct cifsInodeInfo *cinode)
623 {
624         clear_bit(CIFS_INODE_PENDING_OPLOCK_BREAK, &cinode->flags);
625         wake_up_bit(&cinode->flags, CIFS_INODE_PENDING_OPLOCK_BREAK);
626 }
627
628 bool
629 backup_cred(struct cifs_sb_info *cifs_sb)
630 {
631         if (cifs_sb->mnt_cifs_flags & CIFS_MOUNT_CIFS_BACKUPUID) {
632                 if (uid_eq(cifs_sb->ctx->backupuid, current_fsuid()))
633                         return true;
634         }
635         if (cifs_sb->mnt_cifs_flags & CIFS_MOUNT_CIFS_BACKUPGID) {
636                 if (in_group_p(cifs_sb->ctx->backupgid))
637                         return true;
638         }
639
640         return false;
641 }
642
643 void
644 cifs_del_pending_open(struct cifs_pending_open *open)
645 {
646         spin_lock(&tlink_tcon(open->tlink)->open_file_lock);
647         list_del(&open->olist);
648         spin_unlock(&tlink_tcon(open->tlink)->open_file_lock);
649 }
650
651 void
652 cifs_add_pending_open_locked(struct cifs_fid *fid, struct tcon_link *tlink,
653                              struct cifs_pending_open *open)
654 {
655         memcpy(open->lease_key, fid->lease_key, SMB2_LEASE_KEY_SIZE);
656         open->oplock = CIFS_OPLOCK_NO_CHANGE;
657         open->tlink = tlink;
658         fid->pending_open = open;
659         list_add_tail(&open->olist, &tlink_tcon(tlink)->pending_opens);
660 }
661
662 void
663 cifs_add_pending_open(struct cifs_fid *fid, struct tcon_link *tlink,
664                       struct cifs_pending_open *open)
665 {
666         spin_lock(&tlink_tcon(tlink)->open_file_lock);
667         cifs_add_pending_open_locked(fid, tlink, open);
668         spin_unlock(&tlink_tcon(open->tlink)->open_file_lock);
669 }
670
671 /*
672  * Critical section which runs after acquiring deferred_lock.
673  * As there is no reference count on cifs_deferred_close, pdclose
674  * should not be used outside deferred_lock.
675  */
676 bool
677 cifs_is_deferred_close(struct cifsFileInfo *cfile, struct cifs_deferred_close **pdclose)
678 {
679         struct cifs_deferred_close *dclose;
680
681         list_for_each_entry(dclose, &CIFS_I(d_inode(cfile->dentry))->deferred_closes, dlist) {
682                 if ((dclose->netfid == cfile->fid.netfid) &&
683                         (dclose->persistent_fid == cfile->fid.persistent_fid) &&
684                         (dclose->volatile_fid == cfile->fid.volatile_fid)) {
685                         *pdclose = dclose;
686                         return true;
687                 }
688         }
689         return false;
690 }
691
692 /*
693  * Critical section which runs after acquiring deferred_lock.
694  */
695 void
696 cifs_add_deferred_close(struct cifsFileInfo *cfile, struct cifs_deferred_close *dclose)
697 {
698         bool is_deferred = false;
699         struct cifs_deferred_close *pdclose;
700
701         is_deferred = cifs_is_deferred_close(cfile, &pdclose);
702         if (is_deferred) {
703                 kfree(dclose);
704                 return;
705         }
706
707         dclose->tlink = cfile->tlink;
708         dclose->netfid = cfile->fid.netfid;
709         dclose->persistent_fid = cfile->fid.persistent_fid;
710         dclose->volatile_fid = cfile->fid.volatile_fid;
711         list_add_tail(&dclose->dlist, &CIFS_I(d_inode(cfile->dentry))->deferred_closes);
712 }
713
714 /*
715  * Critical section which runs after acquiring deferred_lock.
716  */
717 void
718 cifs_del_deferred_close(struct cifsFileInfo *cfile)
719 {
720         bool is_deferred = false;
721         struct cifs_deferred_close *dclose;
722
723         is_deferred = cifs_is_deferred_close(cfile, &dclose);
724         if (!is_deferred)
725                 return;
726         list_del(&dclose->dlist);
727         kfree(dclose);
728 }
729
730 void
731 cifs_close_deferred_file(struct cifsInodeInfo *cifs_inode)
732 {
733         struct cifsFileInfo *cfile = NULL;
734         struct file_list *tmp_list, *tmp_next_list;
735         struct list_head file_head;
736
737         if (cifs_inode == NULL)
738                 return;
739
740         INIT_LIST_HEAD(&file_head);
741         spin_lock(&cifs_inode->open_file_lock);
742         list_for_each_entry(cfile, &cifs_inode->openFileList, flist) {
743                 if (delayed_work_pending(&cfile->deferred)) {
744                         if (cancel_delayed_work(&cfile->deferred)) {
745                                 spin_lock(&cifs_inode->deferred_lock);
746                                 cifs_del_deferred_close(cfile);
747                                 spin_unlock(&cifs_inode->deferred_lock);
748
749                                 tmp_list = kmalloc(sizeof(struct file_list), GFP_ATOMIC);
750                                 if (tmp_list == NULL)
751                                         break;
752                                 tmp_list->cfile = cfile;
753                                 list_add_tail(&tmp_list->list, &file_head);
754                         }
755                 }
756         }
757         spin_unlock(&cifs_inode->open_file_lock);
758
759         list_for_each_entry_safe(tmp_list, tmp_next_list, &file_head, list) {
760                 _cifsFileInfo_put(tmp_list->cfile, false, false);
761                 list_del(&tmp_list->list);
762                 kfree(tmp_list);
763         }
764 }
765
766 void
767 cifs_close_all_deferred_files(struct cifs_tcon *tcon)
768 {
769         struct cifsFileInfo *cfile;
770         struct file_list *tmp_list, *tmp_next_list;
771         struct list_head file_head;
772
773         INIT_LIST_HEAD(&file_head);
774         spin_lock(&tcon->open_file_lock);
775         list_for_each_entry(cfile, &tcon->openFileList, tlist) {
776                 if (delayed_work_pending(&cfile->deferred)) {
777                         if (cancel_delayed_work(&cfile->deferred)) {
778                                 spin_lock(&CIFS_I(d_inode(cfile->dentry))->deferred_lock);
779                                 cifs_del_deferred_close(cfile);
780                                 spin_unlock(&CIFS_I(d_inode(cfile->dentry))->deferred_lock);
781
782                                 tmp_list = kmalloc(sizeof(struct file_list), GFP_ATOMIC);
783                                 if (tmp_list == NULL)
784                                         break;
785                                 tmp_list->cfile = cfile;
786                                 list_add_tail(&tmp_list->list, &file_head);
787                         }
788                 }
789         }
790         spin_unlock(&tcon->open_file_lock);
791
792         list_for_each_entry_safe(tmp_list, tmp_next_list, &file_head, list) {
793                 _cifsFileInfo_put(tmp_list->cfile, true, false);
794                 list_del(&tmp_list->list);
795                 kfree(tmp_list);
796         }
797 }
798 void
799 cifs_close_deferred_file_under_dentry(struct cifs_tcon *tcon, const char *path)
800 {
801         struct cifsFileInfo *cfile;
802         struct file_list *tmp_list, *tmp_next_list;
803         struct list_head file_head;
804         void *page;
805         const char *full_path;
806
807         INIT_LIST_HEAD(&file_head);
808         page = alloc_dentry_path();
809         spin_lock(&tcon->open_file_lock);
810         list_for_each_entry(cfile, &tcon->openFileList, tlist) {
811                 full_path = build_path_from_dentry(cfile->dentry, page);
812                 if (strstr(full_path, path)) {
813                         if (delayed_work_pending(&cfile->deferred)) {
814                                 if (cancel_delayed_work(&cfile->deferred)) {
815                                         spin_lock(&CIFS_I(d_inode(cfile->dentry))->deferred_lock);
816                                         cifs_del_deferred_close(cfile);
817                                         spin_unlock(&CIFS_I(d_inode(cfile->dentry))->deferred_lock);
818
819                                         tmp_list = kmalloc(sizeof(struct file_list), GFP_ATOMIC);
820                                         if (tmp_list == NULL)
821                                                 break;
822                                         tmp_list->cfile = cfile;
823                                         list_add_tail(&tmp_list->list, &file_head);
824                                 }
825                         }
826                 }
827         }
828         spin_unlock(&tcon->open_file_lock);
829
830         list_for_each_entry_safe(tmp_list, tmp_next_list, &file_head, list) {
831                 _cifsFileInfo_put(tmp_list->cfile, true, false);
832                 list_del(&tmp_list->list);
833                 kfree(tmp_list);
834         }
835         free_dentry_path(page);
836 }
837
838 /* parses DFS referral V3 structure
839  * caller is responsible for freeing target_nodes
840  * returns:
841  * - on success - 0
842  * - on failure - errno
843  */
844 int
845 parse_dfs_referrals(struct get_dfs_referral_rsp *rsp, u32 rsp_size,
846                     unsigned int *num_of_nodes,
847                     struct dfs_info3_param **target_nodes,
848                     const struct nls_table *nls_codepage, int remap,
849                     const char *searchName, bool is_unicode)
850 {
851         int i, rc = 0;
852         char *data_end;
853         struct dfs_referral_level_3 *ref;
854
855         *num_of_nodes = le16_to_cpu(rsp->NumberOfReferrals);
856
857         if (*num_of_nodes < 1) {
858                 cifs_dbg(VFS, "num_referrals: must be at least > 0, but we get num_referrals = %d\n",
859                          *num_of_nodes);
860                 rc = -EINVAL;
861                 goto parse_DFS_referrals_exit;
862         }
863
864         ref = (struct dfs_referral_level_3 *) &(rsp->referrals);
865         if (ref->VersionNumber != cpu_to_le16(3)) {
866                 cifs_dbg(VFS, "Referrals of V%d version are not supported, should be V3\n",
867                          le16_to_cpu(ref->VersionNumber));
868                 rc = -EINVAL;
869                 goto parse_DFS_referrals_exit;
870         }
871
872         /* get the upper boundary of the resp buffer */
873         data_end = (char *)rsp + rsp_size;
874
875         cifs_dbg(FYI, "num_referrals: %d dfs flags: 0x%x ...\n",
876                  *num_of_nodes, le32_to_cpu(rsp->DFSFlags));
877
878         *target_nodes = kcalloc(*num_of_nodes, sizeof(struct dfs_info3_param),
879                                 GFP_KERNEL);
880         if (*target_nodes == NULL) {
881                 rc = -ENOMEM;
882                 goto parse_DFS_referrals_exit;
883         }
884
885         /* collect necessary data from referrals */
886         for (i = 0; i < *num_of_nodes; i++) {
887                 char *temp;
888                 int max_len;
889                 struct dfs_info3_param *node = (*target_nodes)+i;
890
891                 node->flags = le32_to_cpu(rsp->DFSFlags);
892                 if (is_unicode) {
893                         __le16 *tmp = kmalloc(strlen(searchName)*2 + 2,
894                                                 GFP_KERNEL);
895                         if (tmp == NULL) {
896                                 rc = -ENOMEM;
897                                 goto parse_DFS_referrals_exit;
898                         }
899                         cifsConvertToUTF16((__le16 *) tmp, searchName,
900                                            PATH_MAX, nls_codepage, remap);
901                         node->path_consumed = cifs_utf16_bytes(tmp,
902                                         le16_to_cpu(rsp->PathConsumed),
903                                         nls_codepage);
904                         kfree(tmp);
905                 } else
906                         node->path_consumed = le16_to_cpu(rsp->PathConsumed);
907
908                 node->server_type = le16_to_cpu(ref->ServerType);
909                 node->ref_flag = le16_to_cpu(ref->ReferralEntryFlags);
910
911                 /* copy DfsPath */
912                 temp = (char *)ref + le16_to_cpu(ref->DfsPathOffset);
913                 max_len = data_end - temp;
914                 node->path_name = cifs_strndup_from_utf16(temp, max_len,
915                                                 is_unicode, nls_codepage);
916                 if (!node->path_name) {
917                         rc = -ENOMEM;
918                         goto parse_DFS_referrals_exit;
919                 }
920
921                 /* copy link target UNC */
922                 temp = (char *)ref + le16_to_cpu(ref->NetworkAddressOffset);
923                 max_len = data_end - temp;
924                 node->node_name = cifs_strndup_from_utf16(temp, max_len,
925                                                 is_unicode, nls_codepage);
926                 if (!node->node_name) {
927                         rc = -ENOMEM;
928                         goto parse_DFS_referrals_exit;
929                 }
930
931                 node->ttl = le32_to_cpu(ref->TimeToLive);
932
933                 ref++;
934         }
935
936 parse_DFS_referrals_exit:
937         if (rc) {
938                 free_dfs_info_array(*target_nodes, *num_of_nodes);
939                 *target_nodes = NULL;
940                 *num_of_nodes = 0;
941         }
942         return rc;
943 }
944
945 struct cifs_aio_ctx *
946 cifs_aio_ctx_alloc(void)
947 {
948         struct cifs_aio_ctx *ctx;
949
950         /*
951          * Must use kzalloc to initialize ctx->bv to NULL and ctx->direct_io
952          * to false so that we know when we have to unreference pages within
953          * cifs_aio_ctx_release()
954          */
955         ctx = kzalloc(sizeof(struct cifs_aio_ctx), GFP_KERNEL);
956         if (!ctx)
957                 return NULL;
958
959         INIT_LIST_HEAD(&ctx->list);
960         mutex_init(&ctx->aio_mutex);
961         init_completion(&ctx->done);
962         kref_init(&ctx->refcount);
963         return ctx;
964 }
965
966 void
967 cifs_aio_ctx_release(struct kref *refcount)
968 {
969         struct cifs_aio_ctx *ctx = container_of(refcount,
970                                         struct cifs_aio_ctx, refcount);
971
972         cifsFileInfo_put(ctx->cfile);
973
974         /*
975          * ctx->bv is only set if setup_aio_ctx_iter() was call successfuly
976          * which means that iov_iter_get_pages() was a success and thus that
977          * we have taken reference on pages.
978          */
979         if (ctx->bv) {
980                 unsigned i;
981
982                 for (i = 0; i < ctx->npages; i++) {
983                         if (ctx->should_dirty)
984                                 set_page_dirty(ctx->bv[i].bv_page);
985                         put_page(ctx->bv[i].bv_page);
986                 }
987                 kvfree(ctx->bv);
988         }
989
990         kfree(ctx);
991 }
992
993 #define CIFS_AIO_KMALLOC_LIMIT (1024 * 1024)
994
995 int
996 setup_aio_ctx_iter(struct cifs_aio_ctx *ctx, struct iov_iter *iter, int rw)
997 {
998         ssize_t rc;
999         unsigned int cur_npages;
1000         unsigned int npages = 0;
1001         unsigned int i;
1002         size_t len;
1003         size_t count = iov_iter_count(iter);
1004         unsigned int saved_len;
1005         size_t start;
1006         unsigned int max_pages = iov_iter_npages(iter, INT_MAX);
1007         struct page **pages = NULL;
1008         struct bio_vec *bv = NULL;
1009
1010         if (iov_iter_is_kvec(iter)) {
1011                 memcpy(&ctx->iter, iter, sizeof(*iter));
1012                 ctx->len = count;
1013                 iov_iter_advance(iter, count);
1014                 return 0;
1015         }
1016
1017         if (array_size(max_pages, sizeof(*bv)) <= CIFS_AIO_KMALLOC_LIMIT)
1018                 bv = kmalloc_array(max_pages, sizeof(*bv), GFP_KERNEL);
1019
1020         if (!bv) {
1021                 bv = vmalloc(array_size(max_pages, sizeof(*bv)));
1022                 if (!bv)
1023                         return -ENOMEM;
1024         }
1025
1026         if (array_size(max_pages, sizeof(*pages)) <= CIFS_AIO_KMALLOC_LIMIT)
1027                 pages = kmalloc_array(max_pages, sizeof(*pages), GFP_KERNEL);
1028
1029         if (!pages) {
1030                 pages = vmalloc(array_size(max_pages, sizeof(*pages)));
1031                 if (!pages) {
1032                         kvfree(bv);
1033                         return -ENOMEM;
1034                 }
1035         }
1036
1037         saved_len = count;
1038
1039         while (count && npages < max_pages) {
1040                 rc = iov_iter_get_pages2(iter, pages, count, max_pages, &start);
1041                 if (rc < 0) {
1042                         cifs_dbg(VFS, "Couldn't get user pages (rc=%zd)\n", rc);
1043                         break;
1044                 }
1045
1046                 if (rc > count) {
1047                         cifs_dbg(VFS, "get pages rc=%zd more than %zu\n", rc,
1048                                  count);
1049                         break;
1050                 }
1051
1052                 count -= rc;
1053                 rc += start;
1054                 cur_npages = DIV_ROUND_UP(rc, PAGE_SIZE);
1055
1056                 if (npages + cur_npages > max_pages) {
1057                         cifs_dbg(VFS, "out of vec array capacity (%u vs %u)\n",
1058                                  npages + cur_npages, max_pages);
1059                         break;
1060                 }
1061
1062                 for (i = 0; i < cur_npages; i++) {
1063                         len = rc > PAGE_SIZE ? PAGE_SIZE : rc;
1064                         bv[npages + i].bv_page = pages[i];
1065                         bv[npages + i].bv_offset = start;
1066                         bv[npages + i].bv_len = len - start;
1067                         rc -= len;
1068                         start = 0;
1069                 }
1070
1071                 npages += cur_npages;
1072         }
1073
1074         kvfree(pages);
1075         ctx->bv = bv;
1076         ctx->len = saved_len - count;
1077         ctx->npages = npages;
1078         iov_iter_bvec(&ctx->iter, rw, ctx->bv, npages, ctx->len);
1079         return 0;
1080 }
1081
1082 /**
1083  * cifs_alloc_hash - allocate hash and hash context together
1084  * @name: The name of the crypto hash algo
1085  * @sdesc: SHASH descriptor where to put the pointer to the hash TFM
1086  *
1087  * The caller has to make sure @sdesc is initialized to either NULL or
1088  * a valid context. It can be freed via cifs_free_hash().
1089  */
1090 int
1091 cifs_alloc_hash(const char *name, struct shash_desc **sdesc)
1092 {
1093         int rc = 0;
1094         struct crypto_shash *alg = NULL;
1095
1096         if (*sdesc)
1097                 return 0;
1098
1099         alg = crypto_alloc_shash(name, 0, 0);
1100         if (IS_ERR(alg)) {
1101                 cifs_dbg(VFS, "Could not allocate shash TFM '%s'\n", name);
1102                 rc = PTR_ERR(alg);
1103                 *sdesc = NULL;
1104                 return rc;
1105         }
1106
1107         *sdesc = kmalloc(sizeof(struct shash_desc) + crypto_shash_descsize(alg), GFP_KERNEL);
1108         if (*sdesc == NULL) {
1109                 cifs_dbg(VFS, "no memory left to allocate shash TFM '%s'\n", name);
1110                 crypto_free_shash(alg);
1111                 return -ENOMEM;
1112         }
1113
1114         (*sdesc)->tfm = alg;
1115         return 0;
1116 }
1117
1118 /**
1119  * cifs_free_hash - free hash and hash context together
1120  * @sdesc: Where to find the pointer to the hash TFM
1121  *
1122  * Freeing a NULL descriptor is safe.
1123  */
1124 void
1125 cifs_free_hash(struct shash_desc **sdesc)
1126 {
1127         if (unlikely(!sdesc) || !*sdesc)
1128                 return;
1129
1130         if ((*sdesc)->tfm) {
1131                 crypto_free_shash((*sdesc)->tfm);
1132                 (*sdesc)->tfm = NULL;
1133         }
1134
1135         kfree_sensitive(*sdesc);
1136         *sdesc = NULL;
1137 }
1138
1139 /**
1140  * rqst_page_get_length - obtain the length and offset for a page in smb_rqst
1141  * @rqst: The request descriptor
1142  * @page: The index of the page to query
1143  * @len: Where to store the length for this page:
1144  * @offset: Where to store the offset for this page
1145  */
1146 void rqst_page_get_length(const struct smb_rqst *rqst, unsigned int page,
1147                           unsigned int *len, unsigned int *offset)
1148 {
1149         *len = rqst->rq_pagesz;
1150         *offset = (page == 0) ? rqst->rq_offset : 0;
1151
1152         if (rqst->rq_npages == 1 || page == rqst->rq_npages-1)
1153                 *len = rqst->rq_tailsz;
1154         else if (page == 0)
1155                 *len = rqst->rq_pagesz - rqst->rq_offset;
1156 }
1157
1158 void extract_unc_hostname(const char *unc, const char **h, size_t *len)
1159 {
1160         const char *end;
1161
1162         /* skip initial slashes */
1163         while (*unc && (*unc == '\\' || *unc == '/'))
1164                 unc++;
1165
1166         end = unc;
1167
1168         while (*end && !(*end == '\\' || *end == '/'))
1169                 end++;
1170
1171         *h = unc;
1172         *len = end - unc;
1173 }
1174
1175 /**
1176  * copy_path_name - copy src path to dst, possibly truncating
1177  * @dst: The destination buffer
1178  * @src: The source name
1179  *
1180  * returns number of bytes written (including trailing nul)
1181  */
1182 int copy_path_name(char *dst, const char *src)
1183 {
1184         int name_len;
1185
1186         /*
1187          * PATH_MAX includes nul, so if strlen(src) >= PATH_MAX it
1188          * will truncate and strlen(dst) will be PATH_MAX-1
1189          */
1190         name_len = strscpy(dst, src, PATH_MAX);
1191         if (WARN_ON_ONCE(name_len < 0))
1192                 name_len = PATH_MAX-1;
1193
1194         /* we count the trailing nul */
1195         name_len++;
1196         return name_len;
1197 }
1198
1199 struct super_cb_data {
1200         void *data;
1201         struct super_block *sb;
1202 };
1203
1204 static void tcp_super_cb(struct super_block *sb, void *arg)
1205 {
1206         struct super_cb_data *sd = arg;
1207         struct TCP_Server_Info *server = sd->data;
1208         struct cifs_sb_info *cifs_sb;
1209         struct cifs_tcon *tcon;
1210
1211         if (sd->sb)
1212                 return;
1213
1214         cifs_sb = CIFS_SB(sb);
1215         tcon = cifs_sb_master_tcon(cifs_sb);
1216         if (tcon->ses->server == server)
1217                 sd->sb = sb;
1218 }
1219
1220 static struct super_block *__cifs_get_super(void (*f)(struct super_block *, void *),
1221                                             void *data)
1222 {
1223         struct super_cb_data sd = {
1224                 .data = data,
1225                 .sb = NULL,
1226         };
1227         struct file_system_type **fs_type = (struct file_system_type *[]) {
1228                 &cifs_fs_type, &smb3_fs_type, NULL,
1229         };
1230
1231         for (; *fs_type; fs_type++) {
1232                 iterate_supers_type(*fs_type, f, &sd);
1233                 if (sd.sb) {
1234                         /*
1235                          * Grab an active reference in order to prevent automounts (DFS links)
1236                          * of expiring and then freeing up our cifs superblock pointer while
1237                          * we're doing failover.
1238                          */
1239                         cifs_sb_active(sd.sb);
1240                         return sd.sb;
1241                 }
1242         }
1243         return ERR_PTR(-EINVAL);
1244 }
1245
1246 static void __cifs_put_super(struct super_block *sb)
1247 {
1248         if (!IS_ERR_OR_NULL(sb))
1249                 cifs_sb_deactive(sb);
1250 }
1251
1252 struct super_block *cifs_get_tcp_super(struct TCP_Server_Info *server)
1253 {
1254         return __cifs_get_super(tcp_super_cb, server);
1255 }
1256
1257 void cifs_put_tcp_super(struct super_block *sb)
1258 {
1259         __cifs_put_super(sb);
1260 }
1261
1262 #ifdef CONFIG_CIFS_DFS_UPCALL
1263 int match_target_ip(struct TCP_Server_Info *server,
1264                     const char *share, size_t share_len,
1265                     bool *result)
1266 {
1267         int rc;
1268         char *target, *tip = NULL;
1269         struct sockaddr tipaddr;
1270
1271         *result = false;
1272
1273         target = kzalloc(share_len + 3, GFP_KERNEL);
1274         if (!target) {
1275                 rc = -ENOMEM;
1276                 goto out;
1277         }
1278
1279         scnprintf(target, share_len + 3, "\\\\%.*s", (int)share_len, share);
1280
1281         cifs_dbg(FYI, "%s: target name: %s\n", __func__, target + 2);
1282
1283         rc = dns_resolve_server_name_to_ip(target, &tip, NULL);
1284         if (rc < 0)
1285                 goto out;
1286
1287         cifs_dbg(FYI, "%s: target ip: %s\n", __func__, tip);
1288
1289         if (!cifs_convert_address(&tipaddr, tip, strlen(tip))) {
1290                 cifs_dbg(VFS, "%s: failed to convert target ip address\n",
1291                          __func__);
1292                 rc = -EINVAL;
1293                 goto out;
1294         }
1295
1296         *result = cifs_match_ipaddr((struct sockaddr *)&server->dstaddr,
1297                                     &tipaddr);
1298         cifs_dbg(FYI, "%s: ip addresses match: %u\n", __func__, *result);
1299         rc = 0;
1300
1301 out:
1302         kfree(target);
1303         kfree(tip);
1304
1305         return rc;
1306 }
1307
1308 int cifs_update_super_prepath(struct cifs_sb_info *cifs_sb, char *prefix)
1309 {
1310         kfree(cifs_sb->prepath);
1311
1312         if (prefix && *prefix) {
1313                 cifs_sb->prepath = cifs_sanitize_prepath(prefix, GFP_ATOMIC);
1314                 if (!cifs_sb->prepath)
1315                         return -ENOMEM;
1316
1317                 convert_delimiter(cifs_sb->prepath, CIFS_DIR_SEP(cifs_sb));
1318         } else
1319                 cifs_sb->prepath = NULL;
1320
1321         cifs_sb->mnt_cifs_flags |= CIFS_MOUNT_USE_PREFIX_PATH;
1322         return 0;
1323 }
1324
1325 /*
1326  * Handle weird Windows SMB server behaviour. It responds with
1327  * STATUS_OBJECT_NAME_INVALID code to SMB2 QUERY_INFO request for
1328  * "\<server>\<dfsname>\<linkpath>" DFS reference, where <dfsname> contains
1329  * non-ASCII unicode symbols.
1330  */
1331 int cifs_inval_name_dfs_link_error(const unsigned int xid,
1332                                    struct cifs_tcon *tcon,
1333                                    struct cifs_sb_info *cifs_sb,
1334                                    const char *full_path,
1335                                    bool *islink)
1336 {
1337         struct cifs_ses *ses = tcon->ses;
1338         size_t len;
1339         char *path;
1340         char *ref_path;
1341
1342         *islink = false;
1343
1344         /*
1345          * Fast path - skip check when @full_path doesn't have a prefix path to
1346          * look up or tcon is not DFS.
1347          */
1348         if (strlen(full_path) < 2 || !cifs_sb ||
1349             (cifs_sb->mnt_cifs_flags & CIFS_MOUNT_NO_DFS) ||
1350             !is_tcon_dfs(tcon) || !ses->server->origin_fullpath)
1351                 return 0;
1352
1353         /*
1354          * Slow path - tcon is DFS and @full_path has prefix path, so attempt
1355          * to get a referral to figure out whether it is an DFS link.
1356          */
1357         len = strnlen(tcon->tree_name, MAX_TREE_SIZE + 1) + strlen(full_path) + 1;
1358         path = kmalloc(len, GFP_KERNEL);
1359         if (!path)
1360                 return -ENOMEM;
1361
1362         scnprintf(path, len, "%s%s", tcon->tree_name, full_path);
1363         ref_path = dfs_cache_canonical_path(path + 1, cifs_sb->local_nls,
1364                                             cifs_remap(cifs_sb));
1365         kfree(path);
1366
1367         if (IS_ERR(ref_path)) {
1368                 if (PTR_ERR(ref_path) != -EINVAL)
1369                         return PTR_ERR(ref_path);
1370         } else {
1371                 struct dfs_info3_param *refs = NULL;
1372                 int num_refs = 0;
1373
1374                 /*
1375                  * XXX: we are not using dfs_cache_find() here because we might
1376                  * end filling all the DFS cache and thus potentially
1377                  * removing cached DFS targets that the client would eventually
1378                  * need during failover.
1379                  */
1380                 if (ses->server->ops->get_dfs_refer &&
1381                     !ses->server->ops->get_dfs_refer(xid, ses, ref_path, &refs,
1382                                                      &num_refs, cifs_sb->local_nls,
1383                                                      cifs_remap(cifs_sb)))
1384                         *islink = refs[0].server_type == DFS_TYPE_LINK;
1385                 free_dfs_info_array(refs, num_refs);
1386                 kfree(ref_path);
1387         }
1388         return 0;
1389 }
1390 #endif
1391
1392 int cifs_wait_for_server_reconnect(struct TCP_Server_Info *server, bool retry)
1393 {
1394         int timeout = 10;
1395         int rc;
1396
1397         spin_lock(&server->srv_lock);
1398         if (server->tcpStatus != CifsNeedReconnect) {
1399                 spin_unlock(&server->srv_lock);
1400                 return 0;
1401         }
1402         timeout *= server->nr_targets;
1403         spin_unlock(&server->srv_lock);
1404
1405         /*
1406          * Give demultiplex thread up to 10 seconds to each target available for
1407          * reconnect -- should be greater than cifs socket timeout which is 7
1408          * seconds.
1409          *
1410          * On "soft" mounts we wait once. Hard mounts keep retrying until
1411          * process is killed or server comes back on-line.
1412          */
1413         do {
1414                 rc = wait_event_interruptible_timeout(server->response_q,
1415                                                       (server->tcpStatus != CifsNeedReconnect),
1416                                                       timeout * HZ);
1417                 if (rc < 0) {
1418                         cifs_dbg(FYI, "%s: aborting reconnect due to received signal\n",
1419                                  __func__);
1420                         return -ERESTARTSYS;
1421                 }
1422
1423                 /* are we still trying to reconnect? */
1424                 spin_lock(&server->srv_lock);
1425                 if (server->tcpStatus != CifsNeedReconnect) {
1426                         spin_unlock(&server->srv_lock);
1427                         return 0;
1428                 }
1429                 spin_unlock(&server->srv_lock);
1430         } while (retry);
1431
1432         cifs_dbg(FYI, "%s: gave up waiting on reconnect\n", __func__);
1433         return -EHOSTDOWN;
1434 }