drbd: Remove dead code
[firefly-linux-kernel-4.4.55.git] / drivers / block / drbd / drbd_nl.c
1 /*
2    drbd_nl.c
3
4    This file is part of DRBD by Philipp Reisner and Lars Ellenberg.
5
6    Copyright (C) 2001-2008, LINBIT Information Technologies GmbH.
7    Copyright (C) 1999-2008, Philipp Reisner <philipp.reisner@linbit.com>.
8    Copyright (C) 2002-2008, Lars Ellenberg <lars.ellenberg@linbit.com>.
9
10    drbd is free software; you can redistribute it and/or modify
11    it under the terms of the GNU General Public License as published by
12    the Free Software Foundation; either version 2, or (at your option)
13    any later version.
14
15    drbd is distributed in the hope that it will be useful,
16    but WITHOUT ANY WARRANTY; without even the implied warranty of
17    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
18    GNU General Public License for more details.
19
20    You should have received a copy of the GNU General Public License
21    along with drbd; see the file COPYING.  If not, write to
22    the Free Software Foundation, 675 Mass Ave, Cambridge, MA 02139, USA.
23
24  */
25
26 #include <linux/module.h>
27 #include <linux/drbd.h>
28 #include <linux/in.h>
29 #include <linux/fs.h>
30 #include <linux/file.h>
31 #include <linux/slab.h>
32 #include <linux/blkpg.h>
33 #include <linux/cpumask.h>
34 #include "drbd_int.h"
35 #include "drbd_req.h"
36 #include "drbd_wrappers.h"
37 #include <asm/unaligned.h>
38 #include <linux/drbd_limits.h>
39 #include <linux/kthread.h>
40
41 #include <net/genetlink.h>
42
43 /* .doit */
44 // int drbd_adm_create_resource(struct sk_buff *skb, struct genl_info *info);
45 // int drbd_adm_delete_resource(struct sk_buff *skb, struct genl_info *info);
46
47 int drbd_adm_add_minor(struct sk_buff *skb, struct genl_info *info);
48 int drbd_adm_delete_minor(struct sk_buff *skb, struct genl_info *info);
49
50 int drbd_adm_new_resource(struct sk_buff *skb, struct genl_info *info);
51 int drbd_adm_del_resource(struct sk_buff *skb, struct genl_info *info);
52 int drbd_adm_down(struct sk_buff *skb, struct genl_info *info);
53
54 int drbd_adm_set_role(struct sk_buff *skb, struct genl_info *info);
55 int drbd_adm_attach(struct sk_buff *skb, struct genl_info *info);
56 int drbd_adm_disk_opts(struct sk_buff *skb, struct genl_info *info);
57 int drbd_adm_detach(struct sk_buff *skb, struct genl_info *info);
58 int drbd_adm_connect(struct sk_buff *skb, struct genl_info *info);
59 int drbd_adm_net_opts(struct sk_buff *skb, struct genl_info *info);
60 int drbd_adm_resize(struct sk_buff *skb, struct genl_info *info);
61 int drbd_adm_start_ov(struct sk_buff *skb, struct genl_info *info);
62 int drbd_adm_new_c_uuid(struct sk_buff *skb, struct genl_info *info);
63 int drbd_adm_disconnect(struct sk_buff *skb, struct genl_info *info);
64 int drbd_adm_invalidate(struct sk_buff *skb, struct genl_info *info);
65 int drbd_adm_invalidate_peer(struct sk_buff *skb, struct genl_info *info);
66 int drbd_adm_pause_sync(struct sk_buff *skb, struct genl_info *info);
67 int drbd_adm_resume_sync(struct sk_buff *skb, struct genl_info *info);
68 int drbd_adm_suspend_io(struct sk_buff *skb, struct genl_info *info);
69 int drbd_adm_resume_io(struct sk_buff *skb, struct genl_info *info);
70 int drbd_adm_outdate(struct sk_buff *skb, struct genl_info *info);
71 int drbd_adm_resource_opts(struct sk_buff *skb, struct genl_info *info);
72 int drbd_adm_get_status(struct sk_buff *skb, struct genl_info *info);
73 int drbd_adm_get_timeout_type(struct sk_buff *skb, struct genl_info *info);
74 /* .dumpit */
75 int drbd_adm_get_status_all(struct sk_buff *skb, struct netlink_callback *cb);
76
77 #include <linux/drbd_genl_api.h>
78 #include "drbd_nla.h"
79 #include <linux/genl_magic_func.h>
80
81 /* used blkdev_get_by_path, to claim our meta data device(s) */
82 static char *drbd_m_holder = "Hands off! this is DRBD's meta data device.";
83
84 /* Configuration is strictly serialized, because generic netlink message
85  * processing is strictly serialized by the genl_lock().
86  * Which means we can use one static global drbd_config_context struct.
87  */
88 static struct drbd_config_context {
89         /* assigned from drbd_genlmsghdr */
90         unsigned int minor;
91         /* assigned from request attributes, if present */
92         unsigned int volume;
93 #define VOLUME_UNSPECIFIED              (-1U)
94         /* pointer into the request skb,
95          * limited lifetime! */
96         char *resource_name;
97         struct nlattr *my_addr;
98         struct nlattr *peer_addr;
99
100         /* reply buffer */
101         struct sk_buff *reply_skb;
102         /* pointer into reply buffer */
103         struct drbd_genlmsghdr *reply_dh;
104         /* resolved from attributes, if possible */
105         struct drbd_conf *mdev;
106         struct drbd_tconn *tconn;
107 } adm_ctx;
108
109 static void drbd_adm_send_reply(struct sk_buff *skb, struct genl_info *info)
110 {
111         genlmsg_end(skb, genlmsg_data(nlmsg_data(nlmsg_hdr(skb))));
112         if (genlmsg_reply(skb, info))
113                 printk(KERN_ERR "drbd: error sending genl reply\n");
114 }
115
116 /* Used on a fresh "drbd_adm_prepare"d reply_skb, this cannot fail: The only
117  * reason it could fail was no space in skb, and there are 4k available. */
118 int drbd_msg_put_info(const char *info)
119 {
120         struct sk_buff *skb = adm_ctx.reply_skb;
121         struct nlattr *nla;
122         int err = -EMSGSIZE;
123
124         if (!info || !info[0])
125                 return 0;
126
127         nla = nla_nest_start(skb, DRBD_NLA_CFG_REPLY);
128         if (!nla)
129                 return err;
130
131         err = nla_put_string(skb, T_info_text, info);
132         if (err) {
133                 nla_nest_cancel(skb, nla);
134                 return err;
135         } else
136                 nla_nest_end(skb, nla);
137         return 0;
138 }
139
140 /* This would be a good candidate for a "pre_doit" hook,
141  * and per-family private info->pointers.
142  * But we need to stay compatible with older kernels.
143  * If it returns successfully, adm_ctx members are valid.
144  */
145 #define DRBD_ADM_NEED_MINOR     1
146 #define DRBD_ADM_NEED_RESOURCE  2
147 #define DRBD_ADM_NEED_CONNECTION 4
148 static int drbd_adm_prepare(struct sk_buff *skb, struct genl_info *info,
149                 unsigned flags)
150 {
151         struct drbd_genlmsghdr *d_in = info->userhdr;
152         const u8 cmd = info->genlhdr->cmd;
153         int err;
154
155         memset(&adm_ctx, 0, sizeof(adm_ctx));
156
157         /* genl_rcv_msg only checks for CAP_NET_ADMIN on "GENL_ADMIN_PERM" :( */
158         if (cmd != DRBD_ADM_GET_STATUS
159         && security_netlink_recv(skb, CAP_SYS_ADMIN))
160                return -EPERM;
161
162         adm_ctx.reply_skb = genlmsg_new(NLMSG_GOODSIZE, GFP_KERNEL);
163         if (!adm_ctx.reply_skb) {
164                 err = -ENOMEM;
165                 goto fail;
166         }
167
168         adm_ctx.reply_dh = genlmsg_put_reply(adm_ctx.reply_skb,
169                                         info, &drbd_genl_family, 0, cmd);
170         /* put of a few bytes into a fresh skb of >= 4k will always succeed.
171          * but anyways */
172         if (!adm_ctx.reply_dh) {
173                 err = -ENOMEM;
174                 goto fail;
175         }
176
177         adm_ctx.reply_dh->minor = d_in->minor;
178         adm_ctx.reply_dh->ret_code = NO_ERROR;
179
180         adm_ctx.volume = VOLUME_UNSPECIFIED;
181         if (info->attrs[DRBD_NLA_CFG_CONTEXT]) {
182                 struct nlattr *nla;
183                 /* parse and validate only */
184                 err = drbd_cfg_context_from_attrs(NULL, info);
185                 if (err)
186                         goto fail;
187
188                 /* It was present, and valid,
189                  * copy it over to the reply skb. */
190                 err = nla_put_nohdr(adm_ctx.reply_skb,
191                                 info->attrs[DRBD_NLA_CFG_CONTEXT]->nla_len,
192                                 info->attrs[DRBD_NLA_CFG_CONTEXT]);
193                 if (err)
194                         goto fail;
195
196                 /* and assign stuff to the global adm_ctx */
197                 nla = nested_attr_tb[__nla_type(T_ctx_volume)];
198                 if (nla)
199                         adm_ctx.volume = nla_get_u32(nla);
200                 nla = nested_attr_tb[__nla_type(T_ctx_resource_name)];
201                 if (nla)
202                         adm_ctx.resource_name = nla_data(nla);
203                 adm_ctx.my_addr = nested_attr_tb[__nla_type(T_ctx_my_addr)];
204                 adm_ctx.peer_addr = nested_attr_tb[__nla_type(T_ctx_peer_addr)];
205                 if ((adm_ctx.my_addr &&
206                      nla_len(adm_ctx.my_addr) > sizeof(adm_ctx.tconn->my_addr)) ||
207                     (adm_ctx.peer_addr &&
208                      nla_len(adm_ctx.peer_addr) > sizeof(adm_ctx.tconn->peer_addr))) {
209                         err = -EINVAL;
210                         goto fail;
211                 }
212         }
213
214         adm_ctx.minor = d_in->minor;
215         adm_ctx.mdev = minor_to_mdev(d_in->minor);
216         adm_ctx.tconn = conn_get_by_name(adm_ctx.resource_name);
217
218         if (!adm_ctx.mdev && (flags & DRBD_ADM_NEED_MINOR)) {
219                 drbd_msg_put_info("unknown minor");
220                 return ERR_MINOR_INVALID;
221         }
222         if (!adm_ctx.tconn && (flags & DRBD_ADM_NEED_RESOURCE)) {
223                 drbd_msg_put_info("unknown resource");
224                 return ERR_INVALID_REQUEST;
225         }
226
227         if (flags & DRBD_ADM_NEED_CONNECTION) {
228                 if (adm_ctx.tconn && !(flags & DRBD_ADM_NEED_RESOURCE)) {
229                         drbd_msg_put_info("no resource name expected");
230                         return ERR_INVALID_REQUEST;
231                 }
232                 if (adm_ctx.mdev) {
233                         drbd_msg_put_info("no minor number expected");
234                         return ERR_INVALID_REQUEST;
235                 }
236                 if (adm_ctx.my_addr && adm_ctx.peer_addr)
237                         adm_ctx.tconn = conn_get_by_addrs(nla_data(adm_ctx.my_addr),
238                                                           nla_len(adm_ctx.my_addr),
239                                                           nla_data(adm_ctx.peer_addr),
240                                                           nla_len(adm_ctx.peer_addr));
241                 if (!adm_ctx.tconn) {
242                         drbd_msg_put_info("unknown connection");
243                         return ERR_INVALID_REQUEST;
244                 }
245         }
246
247         /* some more paranoia, if the request was over-determined */
248         if (adm_ctx.mdev && adm_ctx.tconn &&
249             adm_ctx.mdev->tconn != adm_ctx.tconn) {
250                 pr_warning("request: minor=%u, resource=%s; but that minor belongs to connection %s\n",
251                                 adm_ctx.minor, adm_ctx.resource_name,
252                                 adm_ctx.mdev->tconn->name);
253                 drbd_msg_put_info("minor exists in different resource");
254                 return ERR_INVALID_REQUEST;
255         }
256         if (adm_ctx.mdev &&
257             adm_ctx.volume != VOLUME_UNSPECIFIED &&
258             adm_ctx.volume != adm_ctx.mdev->vnr) {
259                 pr_warning("request: minor=%u, volume=%u; but that minor is volume %u in %s\n",
260                                 adm_ctx.minor, adm_ctx.volume,
261                                 adm_ctx.mdev->vnr, adm_ctx.mdev->tconn->name);
262                 drbd_msg_put_info("minor exists as different volume");
263                 return ERR_INVALID_REQUEST;
264         }
265
266         return NO_ERROR;
267
268 fail:
269         nlmsg_free(adm_ctx.reply_skb);
270         adm_ctx.reply_skb = NULL;
271         return err;
272 }
273
274 static int drbd_adm_finish(struct genl_info *info, int retcode)
275 {
276         if (adm_ctx.tconn) {
277                 kref_put(&adm_ctx.tconn->kref, &conn_destroy);
278                 adm_ctx.tconn = NULL;
279         }
280
281         if (!adm_ctx.reply_skb)
282                 return -ENOMEM;
283
284         adm_ctx.reply_dh->ret_code = retcode;
285         drbd_adm_send_reply(adm_ctx.reply_skb, info);
286         return 0;
287 }
288
289 static void setup_khelper_env(struct drbd_tconn *tconn, char **envp)
290 {
291         char *afs;
292
293         /* FIXME: A future version will not allow this case. */
294         if (tconn->my_addr_len == 0 || tconn->peer_addr_len == 0)
295                 return;
296
297         switch (((struct sockaddr *)&tconn->peer_addr)->sa_family) {
298         case AF_INET6:
299                 afs = "ipv6";
300                 snprintf(envp[4], 60, "DRBD_PEER_ADDRESS=%pI6",
301                          &((struct sockaddr_in6 *)&tconn->peer_addr)->sin6_addr);
302                 break;
303         case AF_INET:
304                 afs = "ipv4";
305                 snprintf(envp[4], 60, "DRBD_PEER_ADDRESS=%pI4",
306                          &((struct sockaddr_in *)&tconn->peer_addr)->sin_addr);
307                 break;
308         default:
309                 afs = "ssocks";
310                 snprintf(envp[4], 60, "DRBD_PEER_ADDRESS=%pI4",
311                          &((struct sockaddr_in *)&tconn->peer_addr)->sin_addr);
312         }
313         snprintf(envp[3], 20, "DRBD_PEER_AF=%s", afs);
314 }
315
316 int drbd_khelper(struct drbd_conf *mdev, char *cmd)
317 {
318         char *envp[] = { "HOME=/",
319                         "TERM=linux",
320                         "PATH=/sbin:/usr/sbin:/bin:/usr/bin",
321                          (char[20]) { }, /* address family */
322                          (char[60]) { }, /* address */
323                         NULL };
324         char mb[12];
325         char *argv[] = {usermode_helper, cmd, mb, NULL };
326         struct sib_info sib;
327         int ret;
328
329         snprintf(mb, 12, "minor-%d", mdev_to_minor(mdev));
330         setup_khelper_env(mdev->tconn, envp);
331
332         /* The helper may take some time.
333          * write out any unsynced meta data changes now */
334         drbd_md_sync(mdev);
335
336         dev_info(DEV, "helper command: %s %s %s\n", usermode_helper, cmd, mb);
337         sib.sib_reason = SIB_HELPER_PRE;
338         sib.helper_name = cmd;
339         drbd_bcast_event(mdev, &sib);
340         ret = call_usermodehelper(usermode_helper, argv, envp, 1);
341         if (ret)
342                 dev_warn(DEV, "helper command: %s %s %s exit code %u (0x%x)\n",
343                                 usermode_helper, cmd, mb,
344                                 (ret >> 8) & 0xff, ret);
345         else
346                 dev_info(DEV, "helper command: %s %s %s exit code %u (0x%x)\n",
347                                 usermode_helper, cmd, mb,
348                                 (ret >> 8) & 0xff, ret);
349         sib.sib_reason = SIB_HELPER_POST;
350         sib.helper_exit_code = ret;
351         drbd_bcast_event(mdev, &sib);
352
353         if (ret < 0) /* Ignore any ERRNOs we got. */
354                 ret = 0;
355
356         return ret;
357 }
358
359 static void conn_md_sync(struct drbd_tconn *tconn)
360 {
361         struct drbd_conf *mdev;
362         int vnr;
363
364         rcu_read_lock();
365         idr_for_each_entry(&tconn->volumes, mdev, vnr) {
366                 kref_get(&mdev->kref);
367                 rcu_read_unlock();
368                 drbd_md_sync(mdev);
369                 kref_put(&mdev->kref, &drbd_minor_destroy);
370                 rcu_read_lock();
371         }
372         rcu_read_unlock();
373 }
374
375 int conn_khelper(struct drbd_tconn *tconn, char *cmd)
376 {
377         char *envp[] = { "HOME=/",
378                         "TERM=linux",
379                         "PATH=/sbin:/usr/sbin:/bin:/usr/bin",
380                          (char[20]) { }, /* address family */
381                          (char[60]) { }, /* address */
382                         NULL };
383         char *argv[] = {usermode_helper, cmd, tconn->name, NULL };
384         int ret;
385
386         setup_khelper_env(tconn, envp);
387         conn_md_sync(tconn);
388
389         conn_info(tconn, "helper command: %s %s %s\n", usermode_helper, cmd, tconn->name);
390         /* TODO: conn_bcast_event() ?? */
391
392         ret = call_usermodehelper(usermode_helper, argv, envp, 1);
393         if (ret)
394                 conn_warn(tconn, "helper command: %s %s %s exit code %u (0x%x)\n",
395                           usermode_helper, cmd, tconn->name,
396                           (ret >> 8) & 0xff, ret);
397         else
398                 conn_info(tconn, "helper command: %s %s %s exit code %u (0x%x)\n",
399                           usermode_helper, cmd, tconn->name,
400                           (ret >> 8) & 0xff, ret);
401         /* TODO: conn_bcast_event() ?? */
402
403         if (ret < 0) /* Ignore any ERRNOs we got. */
404                 ret = 0;
405
406         return ret;
407 }
408
409 static enum drbd_fencing_p highest_fencing_policy(struct drbd_tconn *tconn)
410 {
411         enum drbd_fencing_p fp = FP_NOT_AVAIL;
412         struct drbd_conf *mdev;
413         int vnr;
414
415         rcu_read_lock();
416         idr_for_each_entry(&tconn->volumes, mdev, vnr) {
417                 if (get_ldev_if_state(mdev, D_CONSISTENT)) {
418                         fp = max_t(enum drbd_fencing_p, fp,
419                                    rcu_dereference(mdev->ldev->disk_conf)->fencing);
420                         put_ldev(mdev);
421                 }
422         }
423         rcu_read_unlock();
424
425         return fp;
426 }
427
428 bool conn_try_outdate_peer(struct drbd_tconn *tconn)
429 {
430         union drbd_state mask = { };
431         union drbd_state val = { };
432         enum drbd_fencing_p fp;
433         char *ex_to_string;
434         int r;
435
436         if (tconn->cstate >= C_WF_REPORT_PARAMS) {
437                 conn_err(tconn, "Expected cstate < C_WF_REPORT_PARAMS\n");
438                 return false;
439         }
440
441         fp = highest_fencing_policy(tconn);
442         switch (fp) {
443         case FP_NOT_AVAIL:
444                 conn_warn(tconn, "Not fencing peer, I'm not even Consistent myself.\n");
445                 goto out;
446         case FP_DONT_CARE:
447                 return true;
448         default: ;
449         }
450
451         r = conn_khelper(tconn, "fence-peer");
452
453         switch ((r>>8) & 0xff) {
454         case 3: /* peer is inconsistent */
455                 ex_to_string = "peer is inconsistent or worse";
456                 mask.pdsk = D_MASK;
457                 val.pdsk = D_INCONSISTENT;
458                 break;
459         case 4: /* peer got outdated, or was already outdated */
460                 ex_to_string = "peer was fenced";
461                 mask.pdsk = D_MASK;
462                 val.pdsk = D_OUTDATED;
463                 break;
464         case 5: /* peer was down */
465                 if (conn_highest_disk(tconn) == D_UP_TO_DATE) {
466                         /* we will(have) create(d) a new UUID anyways... */
467                         ex_to_string = "peer is unreachable, assumed to be dead";
468                         mask.pdsk = D_MASK;
469                         val.pdsk = D_OUTDATED;
470                 } else {
471                         ex_to_string = "peer unreachable, doing nothing since disk != UpToDate";
472                 }
473                 break;
474         case 6: /* Peer is primary, voluntarily outdate myself.
475                  * This is useful when an unconnected R_SECONDARY is asked to
476                  * become R_PRIMARY, but finds the other peer being active. */
477                 ex_to_string = "peer is active";
478                 conn_warn(tconn, "Peer is primary, outdating myself.\n");
479                 mask.disk = D_MASK;
480                 val.disk = D_OUTDATED;
481                 break;
482         case 7:
483                 if (fp != FP_STONITH)
484                         conn_err(tconn, "fence-peer() = 7 && fencing != Stonith !!!\n");
485                 ex_to_string = "peer was stonithed";
486                 mask.pdsk = D_MASK;
487                 val.pdsk = D_OUTDATED;
488                 break;
489         default:
490                 /* The script is broken ... */
491                 conn_err(tconn, "fence-peer helper broken, returned %d\n", (r>>8)&0xff);
492                 return false; /* Eventually leave IO frozen */
493         }
494
495         conn_info(tconn, "fence-peer helper returned %d (%s)\n",
496                   (r>>8) & 0xff, ex_to_string);
497
498  out:
499
500         /* Not using
501            conn_request_state(tconn, mask, val, CS_VERBOSE);
502            here, because we might were able to re-establish the connection in the
503            meantime. */
504         spin_lock_irq(&tconn->req_lock);
505         if (tconn->cstate < C_WF_REPORT_PARAMS)
506                 _conn_request_state(tconn, mask, val, CS_VERBOSE);
507         spin_unlock_irq(&tconn->req_lock);
508
509         return conn_highest_pdsk(tconn) <= D_OUTDATED;
510 }
511
512 static int _try_outdate_peer_async(void *data)
513 {
514         struct drbd_tconn *tconn = (struct drbd_tconn *)data;
515
516         conn_try_outdate_peer(tconn);
517
518         kref_put(&tconn->kref, &conn_destroy);
519         return 0;
520 }
521
522 void conn_try_outdate_peer_async(struct drbd_tconn *tconn)
523 {
524         struct task_struct *opa;
525
526         kref_get(&tconn->kref);
527         opa = kthread_run(_try_outdate_peer_async, tconn, "drbd_async_h");
528         if (IS_ERR(opa)) {
529                 conn_err(tconn, "out of mem, failed to invoke fence-peer helper\n");
530                 kref_put(&tconn->kref, &conn_destroy);
531         }
532 }
533
534 enum drbd_state_rv
535 drbd_set_role(struct drbd_conf *mdev, enum drbd_role new_role, int force)
536 {
537         const int max_tries = 4;
538         enum drbd_state_rv rv = SS_UNKNOWN_ERROR;
539         struct net_conf *nc;
540         int try = 0;
541         int forced = 0;
542         union drbd_state mask, val;
543
544         if (new_role == R_PRIMARY)
545                 request_ping(mdev->tconn); /* Detect a dead peer ASAP */
546
547         mutex_lock(mdev->state_mutex);
548
549         mask.i = 0; mask.role = R_MASK;
550         val.i  = 0; val.role  = new_role;
551
552         while (try++ < max_tries) {
553                 rv = _drbd_request_state(mdev, mask, val, CS_WAIT_COMPLETE);
554
555                 /* in case we first succeeded to outdate,
556                  * but now suddenly could establish a connection */
557                 if (rv == SS_CW_FAILED_BY_PEER && mask.pdsk != 0) {
558                         val.pdsk = 0;
559                         mask.pdsk = 0;
560                         continue;
561                 }
562
563                 if (rv == SS_NO_UP_TO_DATE_DISK && force &&
564                     (mdev->state.disk < D_UP_TO_DATE &&
565                      mdev->state.disk >= D_INCONSISTENT)) {
566                         mask.disk = D_MASK;
567                         val.disk  = D_UP_TO_DATE;
568                         forced = 1;
569                         continue;
570                 }
571
572                 if (rv == SS_NO_UP_TO_DATE_DISK &&
573                     mdev->state.disk == D_CONSISTENT && mask.pdsk == 0) {
574                         D_ASSERT(mdev->state.pdsk == D_UNKNOWN);
575
576                         if (conn_try_outdate_peer(mdev->tconn)) {
577                                 val.disk = D_UP_TO_DATE;
578                                 mask.disk = D_MASK;
579                         }
580                         continue;
581                 }
582
583                 if (rv == SS_NOTHING_TO_DO)
584                         goto out;
585                 if (rv == SS_PRIMARY_NOP && mask.pdsk == 0) {
586                         if (!conn_try_outdate_peer(mdev->tconn) && force) {
587                                 dev_warn(DEV, "Forced into split brain situation!\n");
588                                 mask.pdsk = D_MASK;
589                                 val.pdsk  = D_OUTDATED;
590
591                         }
592                         continue;
593                 }
594                 if (rv == SS_TWO_PRIMARIES) {
595                         /* Maybe the peer is detected as dead very soon...
596                            retry at most once more in this case. */
597                         int timeo;
598                         rcu_read_lock();
599                         nc = rcu_dereference(mdev->tconn->net_conf);
600                         timeo = nc ? (nc->ping_timeo + 1) * HZ / 10 : 1;
601                         rcu_read_unlock();
602                         schedule_timeout_interruptible(timeo);
603                         if (try < max_tries)
604                                 try = max_tries - 1;
605                         continue;
606                 }
607                 if (rv < SS_SUCCESS) {
608                         rv = _drbd_request_state(mdev, mask, val,
609                                                 CS_VERBOSE + CS_WAIT_COMPLETE);
610                         if (rv < SS_SUCCESS)
611                                 goto out;
612                 }
613                 break;
614         }
615
616         if (rv < SS_SUCCESS)
617                 goto out;
618
619         if (forced)
620                 dev_warn(DEV, "Forced to consider local data as UpToDate!\n");
621
622         /* Wait until nothing is on the fly :) */
623         wait_event(mdev->misc_wait, atomic_read(&mdev->ap_pending_cnt) == 0);
624
625         if (new_role == R_SECONDARY) {
626                 set_disk_ro(mdev->vdisk, true);
627                 if (get_ldev(mdev)) {
628                         mdev->ldev->md.uuid[UI_CURRENT] &= ~(u64)1;
629                         put_ldev(mdev);
630                 }
631         } else {
632                 mutex_lock(&mdev->tconn->conf_update);
633                 nc = mdev->tconn->net_conf;
634                 if (nc)
635                         nc->discard_my_data = 0; /* without copy; single bit op is atomic */
636                 mutex_unlock(&mdev->tconn->conf_update);
637
638                 set_disk_ro(mdev->vdisk, false);
639                 if (get_ldev(mdev)) {
640                         if (((mdev->state.conn < C_CONNECTED ||
641                                mdev->state.pdsk <= D_FAILED)
642                               && mdev->ldev->md.uuid[UI_BITMAP] == 0) || forced)
643                                 drbd_uuid_new_current(mdev);
644
645                         mdev->ldev->md.uuid[UI_CURRENT] |=  (u64)1;
646                         put_ldev(mdev);
647                 }
648         }
649
650         /* writeout of activity log covered areas of the bitmap
651          * to stable storage done in after state change already */
652
653         if (mdev->state.conn >= C_WF_REPORT_PARAMS) {
654                 /* if this was forced, we should consider sync */
655                 if (forced)
656                         drbd_send_uuids(mdev);
657                 drbd_send_state(mdev);
658         }
659
660         drbd_md_sync(mdev);
661
662         kobject_uevent(&disk_to_dev(mdev->vdisk)->kobj, KOBJ_CHANGE);
663 out:
664         mutex_unlock(mdev->state_mutex);
665         return rv;
666 }
667
668 static const char *from_attrs_err_to_txt(int err)
669 {
670         return  err == -ENOMSG ? "required attribute missing" :
671                 err == -EOPNOTSUPP ? "unknown mandatory attribute" :
672                 err == -EEXIST ? "can not change invariant setting" :
673                 "invalid attribute value";
674 }
675
676 int drbd_adm_set_role(struct sk_buff *skb, struct genl_info *info)
677 {
678         struct set_role_parms parms;
679         int err;
680         enum drbd_ret_code retcode;
681
682         retcode = drbd_adm_prepare(skb, info, DRBD_ADM_NEED_MINOR);
683         if (!adm_ctx.reply_skb)
684                 return retcode;
685         if (retcode != NO_ERROR)
686                 goto out;
687
688         memset(&parms, 0, sizeof(parms));
689         if (info->attrs[DRBD_NLA_SET_ROLE_PARMS]) {
690                 err = set_role_parms_from_attrs(&parms, info);
691                 if (err) {
692                         retcode = ERR_MANDATORY_TAG;
693                         drbd_msg_put_info(from_attrs_err_to_txt(err));
694                         goto out;
695                 }
696         }
697
698         if (info->genlhdr->cmd == DRBD_ADM_PRIMARY)
699                 retcode = drbd_set_role(adm_ctx.mdev, R_PRIMARY, parms.assume_uptodate);
700         else
701                 retcode = drbd_set_role(adm_ctx.mdev, R_SECONDARY, 0);
702 out:
703         drbd_adm_finish(info, retcode);
704         return 0;
705 }
706
707 /* initializes the md.*_offset members, so we are able to find
708  * the on disk meta data */
709 static void drbd_md_set_sector_offsets(struct drbd_conf *mdev,
710                                        struct drbd_backing_dev *bdev)
711 {
712         sector_t md_size_sect = 0;
713         int meta_dev_idx;
714
715         rcu_read_lock();
716         meta_dev_idx = rcu_dereference(bdev->disk_conf)->meta_dev_idx;
717
718         switch (meta_dev_idx) {
719         default:
720                 /* v07 style fixed size indexed meta data */
721                 bdev->md.md_size_sect = MD_RESERVED_SECT;
722                 bdev->md.md_offset = drbd_md_ss__(mdev, bdev);
723                 bdev->md.al_offset = MD_AL_OFFSET;
724                 bdev->md.bm_offset = MD_BM_OFFSET;
725                 break;
726         case DRBD_MD_INDEX_FLEX_EXT:
727                 /* just occupy the full device; unit: sectors */
728                 bdev->md.md_size_sect = drbd_get_capacity(bdev->md_bdev);
729                 bdev->md.md_offset = 0;
730                 bdev->md.al_offset = MD_AL_OFFSET;
731                 bdev->md.bm_offset = MD_BM_OFFSET;
732                 break;
733         case DRBD_MD_INDEX_INTERNAL:
734         case DRBD_MD_INDEX_FLEX_INT:
735                 bdev->md.md_offset = drbd_md_ss__(mdev, bdev);
736                 /* al size is still fixed */
737                 bdev->md.al_offset = -MD_AL_SECTORS;
738                 /* we need (slightly less than) ~ this much bitmap sectors: */
739                 md_size_sect = drbd_get_capacity(bdev->backing_bdev);
740                 md_size_sect = ALIGN(md_size_sect, BM_SECT_PER_EXT);
741                 md_size_sect = BM_SECT_TO_EXT(md_size_sect);
742                 md_size_sect = ALIGN(md_size_sect, 8);
743
744                 /* plus the "drbd meta data super block",
745                  * and the activity log; */
746                 md_size_sect += MD_BM_OFFSET;
747
748                 bdev->md.md_size_sect = md_size_sect;
749                 /* bitmap offset is adjusted by 'super' block size */
750                 bdev->md.bm_offset   = -md_size_sect + MD_AL_OFFSET;
751                 break;
752         }
753         rcu_read_unlock();
754 }
755
756 /* input size is expected to be in KB */
757 char *ppsize(char *buf, unsigned long long size)
758 {
759         /* Needs 9 bytes at max including trailing NUL:
760          * -1ULL ==> "16384 EB" */
761         static char units[] = { 'K', 'M', 'G', 'T', 'P', 'E' };
762         int base = 0;
763         while (size >= 10000 && base < sizeof(units)-1) {
764                 /* shift + round */
765                 size = (size >> 10) + !!(size & (1<<9));
766                 base++;
767         }
768         sprintf(buf, "%u %cB", (unsigned)size, units[base]);
769
770         return buf;
771 }
772
773 /* there is still a theoretical deadlock when called from receiver
774  * on an D_INCONSISTENT R_PRIMARY:
775  *  remote READ does inc_ap_bio, receiver would need to receive answer
776  *  packet from remote to dec_ap_bio again.
777  *  receiver receive_sizes(), comes here,
778  *  waits for ap_bio_cnt == 0. -> deadlock.
779  * but this cannot happen, actually, because:
780  *  R_PRIMARY D_INCONSISTENT, and peer's disk is unreachable
781  *  (not connected, or bad/no disk on peer):
782  *  see drbd_fail_request_early, ap_bio_cnt is zero.
783  *  R_PRIMARY D_INCONSISTENT, and C_SYNC_TARGET:
784  *  peer may not initiate a resize.
785  */
786 /* Note these are not to be confused with
787  * drbd_adm_suspend_io/drbd_adm_resume_io,
788  * which are (sub) state changes triggered by admin (drbdsetup),
789  * and can be long lived.
790  * This changes an mdev->flag, is triggered by drbd internals,
791  * and should be short-lived. */
792 void drbd_suspend_io(struct drbd_conf *mdev)
793 {
794         set_bit(SUSPEND_IO, &mdev->flags);
795         if (drbd_suspended(mdev))
796                 return;
797         wait_event(mdev->misc_wait, !atomic_read(&mdev->ap_bio_cnt));
798 }
799
800 void drbd_resume_io(struct drbd_conf *mdev)
801 {
802         clear_bit(SUSPEND_IO, &mdev->flags);
803         wake_up(&mdev->misc_wait);
804 }
805
806 /**
807  * drbd_determine_dev_size() -  Sets the right device size obeying all constraints
808  * @mdev:       DRBD device.
809  *
810  * Returns 0 on success, negative return values indicate errors.
811  * You should call drbd_md_sync() after calling this function.
812  */
813 enum determine_dev_size drbd_determine_dev_size(struct drbd_conf *mdev, enum dds_flags flags) __must_hold(local)
814 {
815         sector_t prev_first_sect, prev_size; /* previous meta location */
816         sector_t la_size, u_size;
817         sector_t size;
818         char ppb[10];
819
820         int md_moved, la_size_changed;
821         enum determine_dev_size rv = unchanged;
822
823         /* race:
824          * application request passes inc_ap_bio,
825          * but then cannot get an AL-reference.
826          * this function later may wait on ap_bio_cnt == 0. -> deadlock.
827          *
828          * to avoid that:
829          * Suspend IO right here.
830          * still lock the act_log to not trigger ASSERTs there.
831          */
832         drbd_suspend_io(mdev);
833
834         /* no wait necessary anymore, actually we could assert that */
835         wait_event(mdev->al_wait, lc_try_lock(mdev->act_log));
836
837         prev_first_sect = drbd_md_first_sector(mdev->ldev);
838         prev_size = mdev->ldev->md.md_size_sect;
839         la_size = mdev->ldev->md.la_size_sect;
840
841         /* TODO: should only be some assert here, not (re)init... */
842         drbd_md_set_sector_offsets(mdev, mdev->ldev);
843
844         rcu_read_lock();
845         u_size = rcu_dereference(mdev->ldev->disk_conf)->disk_size;
846         rcu_read_unlock();
847         size = drbd_new_dev_size(mdev, mdev->ldev, u_size, flags & DDSF_FORCED);
848
849         if (drbd_get_capacity(mdev->this_bdev) != size ||
850             drbd_bm_capacity(mdev) != size) {
851                 int err;
852                 err = drbd_bm_resize(mdev, size, !(flags & DDSF_NO_RESYNC));
853                 if (unlikely(err)) {
854                         /* currently there is only one error: ENOMEM! */
855                         size = drbd_bm_capacity(mdev)>>1;
856                         if (size == 0) {
857                                 dev_err(DEV, "OUT OF MEMORY! "
858                                     "Could not allocate bitmap!\n");
859                         } else {
860                                 dev_err(DEV, "BM resizing failed. "
861                                     "Leaving size unchanged at size = %lu KB\n",
862                                     (unsigned long)size);
863                         }
864                         rv = dev_size_error;
865                 }
866                 /* racy, see comments above. */
867                 drbd_set_my_capacity(mdev, size);
868                 mdev->ldev->md.la_size_sect = size;
869                 dev_info(DEV, "size = %s (%llu KB)\n", ppsize(ppb, size>>1),
870                      (unsigned long long)size>>1);
871         }
872         if (rv == dev_size_error)
873                 goto out;
874
875         la_size_changed = (la_size != mdev->ldev->md.la_size_sect);
876
877         md_moved = prev_first_sect != drbd_md_first_sector(mdev->ldev)
878                 || prev_size       != mdev->ldev->md.md_size_sect;
879
880         if (la_size_changed || md_moved) {
881                 int err;
882
883                 drbd_al_shrink(mdev); /* All extents inactive. */
884                 dev_info(DEV, "Writing the whole bitmap, %s\n",
885                          la_size_changed && md_moved ? "size changed and md moved" :
886                          la_size_changed ? "size changed" : "md moved");
887                 /* next line implicitly does drbd_suspend_io()+drbd_resume_io() */
888                 err = drbd_bitmap_io(mdev, &drbd_bm_write,
889                                 "size changed", BM_LOCKED_MASK);
890                 if (err) {
891                         rv = dev_size_error;
892                         goto out;
893                 }
894                 drbd_md_mark_dirty(mdev);
895         }
896
897         if (size > la_size)
898                 rv = grew;
899         if (size < la_size)
900                 rv = shrunk;
901 out:
902         lc_unlock(mdev->act_log);
903         wake_up(&mdev->al_wait);
904         drbd_resume_io(mdev);
905
906         return rv;
907 }
908
909 sector_t
910 drbd_new_dev_size(struct drbd_conf *mdev, struct drbd_backing_dev *bdev,
911                   sector_t u_size, int assume_peer_has_space)
912 {
913         sector_t p_size = mdev->p_size;   /* partner's disk size. */
914         sector_t la_size = bdev->md.la_size_sect; /* last agreed size. */
915         sector_t m_size; /* my size */
916         sector_t size = 0;
917
918         m_size = drbd_get_max_capacity(bdev);
919
920         if (mdev->state.conn < C_CONNECTED && assume_peer_has_space) {
921                 dev_warn(DEV, "Resize while not connected was forced by the user!\n");
922                 p_size = m_size;
923         }
924
925         if (p_size && m_size) {
926                 size = min_t(sector_t, p_size, m_size);
927         } else {
928                 if (la_size) {
929                         size = la_size;
930                         if (m_size && m_size < size)
931                                 size = m_size;
932                         if (p_size && p_size < size)
933                                 size = p_size;
934                 } else {
935                         if (m_size)
936                                 size = m_size;
937                         if (p_size)
938                                 size = p_size;
939                 }
940         }
941
942         if (size == 0)
943                 dev_err(DEV, "Both nodes diskless!\n");
944
945         if (u_size) {
946                 if (u_size > size)
947                         dev_err(DEV, "Requested disk size is too big (%lu > %lu)\n",
948                             (unsigned long)u_size>>1, (unsigned long)size>>1);
949                 else
950                         size = u_size;
951         }
952
953         return size;
954 }
955
956 /**
957  * drbd_check_al_size() - Ensures that the AL is of the right size
958  * @mdev:       DRBD device.
959  *
960  * Returns -EBUSY if current al lru is still used, -ENOMEM when allocation
961  * failed, and 0 on success. You should call drbd_md_sync() after you called
962  * this function.
963  */
964 static int drbd_check_al_size(struct drbd_conf *mdev, struct disk_conf *dc)
965 {
966         struct lru_cache *n, *t;
967         struct lc_element *e;
968         unsigned int in_use;
969         int i;
970
971         if (mdev->act_log &&
972             mdev->act_log->nr_elements == dc->al_extents)
973                 return 0;
974
975         in_use = 0;
976         t = mdev->act_log;
977         n = lc_create("act_log", drbd_al_ext_cache, AL_UPDATES_PER_TRANSACTION,
978                 dc->al_extents, sizeof(struct lc_element), 0);
979
980         if (n == NULL) {
981                 dev_err(DEV, "Cannot allocate act_log lru!\n");
982                 return -ENOMEM;
983         }
984         spin_lock_irq(&mdev->al_lock);
985         if (t) {
986                 for (i = 0; i < t->nr_elements; i++) {
987                         e = lc_element_by_index(t, i);
988                         if (e->refcnt)
989                                 dev_err(DEV, "refcnt(%d)==%d\n",
990                                     e->lc_number, e->refcnt);
991                         in_use += e->refcnt;
992                 }
993         }
994         if (!in_use)
995                 mdev->act_log = n;
996         spin_unlock_irq(&mdev->al_lock);
997         if (in_use) {
998                 dev_err(DEV, "Activity log still in use!\n");
999                 lc_destroy(n);
1000                 return -EBUSY;
1001         } else {
1002                 if (t)
1003                         lc_destroy(t);
1004         }
1005         drbd_md_mark_dirty(mdev); /* we changed mdev->act_log->nr_elemens */
1006         return 0;
1007 }
1008
1009 static void drbd_setup_queue_param(struct drbd_conf *mdev, unsigned int max_bio_size)
1010 {
1011         struct request_queue * const q = mdev->rq_queue;
1012         int max_hw_sectors = max_bio_size >> 9;
1013         int max_segments = 0;
1014
1015         if (get_ldev_if_state(mdev, D_ATTACHING)) {
1016                 struct request_queue * const b = mdev->ldev->backing_bdev->bd_disk->queue;
1017
1018                 max_hw_sectors = min(queue_max_hw_sectors(b), max_bio_size >> 9);
1019                 rcu_read_lock();
1020                 max_segments = rcu_dereference(mdev->ldev->disk_conf)->max_bio_bvecs;
1021                 rcu_read_unlock();
1022                 put_ldev(mdev);
1023         }
1024
1025         blk_queue_logical_block_size(q, 512);
1026         blk_queue_max_hw_sectors(q, max_hw_sectors);
1027         /* This is the workaround for "bio would need to, but cannot, be split" */
1028         blk_queue_max_segments(q, max_segments ? max_segments : BLK_MAX_SEGMENTS);
1029         blk_queue_segment_boundary(q, PAGE_CACHE_SIZE-1);
1030
1031         if (get_ldev_if_state(mdev, D_ATTACHING)) {
1032                 struct request_queue * const b = mdev->ldev->backing_bdev->bd_disk->queue;
1033
1034                 blk_queue_stack_limits(q, b);
1035
1036                 if (q->backing_dev_info.ra_pages != b->backing_dev_info.ra_pages) {
1037                         dev_info(DEV, "Adjusting my ra_pages to backing device's (%lu -> %lu)\n",
1038                                  q->backing_dev_info.ra_pages,
1039                                  b->backing_dev_info.ra_pages);
1040                         q->backing_dev_info.ra_pages = b->backing_dev_info.ra_pages;
1041                 }
1042                 put_ldev(mdev);
1043         }
1044 }
1045
1046 void drbd_reconsider_max_bio_size(struct drbd_conf *mdev)
1047 {
1048         int now, new, local, peer;
1049
1050         now = queue_max_hw_sectors(mdev->rq_queue) << 9;
1051         local = mdev->local_max_bio_size; /* Eventually last known value, from volatile memory */
1052         peer = mdev->peer_max_bio_size; /* Eventually last known value, from meta data */
1053
1054         if (get_ldev_if_state(mdev, D_ATTACHING)) {
1055                 local = queue_max_hw_sectors(mdev->ldev->backing_bdev->bd_disk->queue) << 9;
1056                 mdev->local_max_bio_size = local;
1057                 put_ldev(mdev);
1058         }
1059
1060         /* We may ignore peer limits if the peer is modern enough.
1061            Because new from 8.3.8 onwards the peer can use multiple
1062            BIOs for a single peer_request */
1063         if (mdev->state.conn >= C_CONNECTED) {
1064                 if (mdev->tconn->agreed_pro_version < 94)
1065                         peer = mdev->peer_max_bio_size;
1066                 else if (mdev->tconn->agreed_pro_version == 94)
1067                         peer = DRBD_MAX_SIZE_H80_PACKET;
1068                 else /* drbd 8.3.8 onwards */
1069                         peer = DRBD_MAX_BIO_SIZE;
1070         }
1071
1072         new = min_t(int, local, peer);
1073
1074         if (mdev->state.role == R_PRIMARY && new < now)
1075                 dev_err(DEV, "ASSERT FAILED new < now; (%d < %d)\n", new, now);
1076
1077         if (new != now)
1078                 dev_info(DEV, "max BIO size = %u\n", new);
1079
1080         drbd_setup_queue_param(mdev, new);
1081 }
1082
1083 /* Starts the worker thread */
1084 static void conn_reconfig_start(struct drbd_tconn *tconn)
1085 {
1086         drbd_thread_start(&tconn->worker);
1087         conn_flush_workqueue(tconn);
1088 }
1089
1090 /* if still unconfigured, stops worker again. */
1091 static void conn_reconfig_done(struct drbd_tconn *tconn)
1092 {
1093         bool stop_threads;
1094         spin_lock_irq(&tconn->req_lock);
1095         stop_threads = conn_all_vols_unconf(tconn);
1096         spin_unlock_irq(&tconn->req_lock);
1097         if (stop_threads) {
1098                 /* asender is implicitly stopped by receiver
1099                  * in conn_disconnect() */
1100                 drbd_thread_stop(&tconn->receiver);
1101                 drbd_thread_stop(&tconn->worker);
1102         }
1103 }
1104
1105 /* Make sure IO is suspended before calling this function(). */
1106 static void drbd_suspend_al(struct drbd_conf *mdev)
1107 {
1108         int s = 0;
1109
1110         if (!lc_try_lock(mdev->act_log)) {
1111                 dev_warn(DEV, "Failed to lock al in drbd_suspend_al()\n");
1112                 return;
1113         }
1114
1115         drbd_al_shrink(mdev);
1116         spin_lock_irq(&mdev->tconn->req_lock);
1117         if (mdev->state.conn < C_CONNECTED)
1118                 s = !test_and_set_bit(AL_SUSPENDED, &mdev->flags);
1119         spin_unlock_irq(&mdev->tconn->req_lock);
1120         lc_unlock(mdev->act_log);
1121
1122         if (s)
1123                 dev_info(DEV, "Suspended AL updates\n");
1124 }
1125
1126
1127 static bool should_set_defaults(struct genl_info *info)
1128 {
1129         unsigned flags = ((struct drbd_genlmsghdr*)info->userhdr)->flags;
1130         return 0 != (flags & DRBD_GENL_F_SET_DEFAULTS);
1131 }
1132
1133 static void enforce_disk_conf_limits(struct disk_conf *dc)
1134 {
1135         if (dc->al_extents < DRBD_AL_EXTENTS_MIN)
1136                 dc->al_extents = DRBD_AL_EXTENTS_MIN;
1137         if (dc->al_extents > DRBD_AL_EXTENTS_MAX)
1138                 dc->al_extents = DRBD_AL_EXTENTS_MAX;
1139
1140         if (dc->c_plan_ahead > DRBD_C_PLAN_AHEAD_MAX)
1141                 dc->c_plan_ahead = DRBD_C_PLAN_AHEAD_MAX;
1142 }
1143
1144 int drbd_adm_disk_opts(struct sk_buff *skb, struct genl_info *info)
1145 {
1146         enum drbd_ret_code retcode;
1147         struct drbd_conf *mdev;
1148         struct disk_conf *new_disk_conf, *old_disk_conf;
1149         struct fifo_buffer *old_plan = NULL, *new_plan = NULL;
1150         int err, fifo_size;
1151
1152         retcode = drbd_adm_prepare(skb, info, DRBD_ADM_NEED_MINOR);
1153         if (!adm_ctx.reply_skb)
1154                 return retcode;
1155         if (retcode != NO_ERROR)
1156                 goto out;
1157
1158         mdev = adm_ctx.mdev;
1159
1160         /* we also need a disk
1161          * to change the options on */
1162         if (!get_ldev(mdev)) {
1163                 retcode = ERR_NO_DISK;
1164                 goto out;
1165         }
1166
1167         new_disk_conf = kmalloc(sizeof(struct disk_conf), GFP_KERNEL);
1168         if (!new_disk_conf) {
1169                 retcode = ERR_NOMEM;
1170                 goto fail;
1171         }
1172
1173         mutex_lock(&mdev->tconn->conf_update);
1174         old_disk_conf = mdev->ldev->disk_conf;
1175         *new_disk_conf = *old_disk_conf;
1176         if (should_set_defaults(info))
1177                 set_disk_conf_defaults(new_disk_conf);
1178
1179         err = disk_conf_from_attrs_for_change(new_disk_conf, info);
1180         if (err && err != -ENOMSG) {
1181                 retcode = ERR_MANDATORY_TAG;
1182                 drbd_msg_put_info(from_attrs_err_to_txt(err));
1183         }
1184
1185         if (!expect(new_disk_conf->resync_rate >= 1))
1186                 new_disk_conf->resync_rate = 1;
1187
1188         enforce_disk_conf_limits(new_disk_conf);
1189
1190         fifo_size = (new_disk_conf->c_plan_ahead * 10 * SLEEP_TIME) / HZ;
1191         if (fifo_size != mdev->rs_plan_s->size) {
1192                 new_plan = fifo_alloc(fifo_size);
1193                 if (!new_plan) {
1194                         dev_err(DEV, "kmalloc of fifo_buffer failed");
1195                         retcode = ERR_NOMEM;
1196                         goto fail_unlock;
1197                 }
1198         }
1199
1200         wait_event(mdev->al_wait, lc_try_lock(mdev->act_log));
1201         drbd_al_shrink(mdev);
1202         err = drbd_check_al_size(mdev, new_disk_conf);
1203         lc_unlock(mdev->act_log);
1204         wake_up(&mdev->al_wait);
1205
1206         if (err) {
1207                 retcode = ERR_NOMEM;
1208                 goto fail_unlock;
1209         }
1210
1211         write_lock_irq(&global_state_lock);
1212         retcode = drbd_resync_after_valid(mdev, new_disk_conf->resync_after);
1213         if (retcode == NO_ERROR) {
1214                 rcu_assign_pointer(mdev->ldev->disk_conf, new_disk_conf);
1215                 drbd_resync_after_changed(mdev);
1216         }
1217         write_unlock_irq(&global_state_lock);
1218
1219         if (retcode != NO_ERROR)
1220                 goto fail_unlock;
1221
1222         if (new_plan) {
1223                 old_plan = mdev->rs_plan_s;
1224                 rcu_assign_pointer(mdev->rs_plan_s, new_plan);
1225         }
1226
1227         mutex_unlock(&mdev->tconn->conf_update);
1228         drbd_md_sync(mdev);
1229
1230         if (mdev->state.conn >= C_CONNECTED)
1231                 drbd_send_sync_param(mdev);
1232
1233         synchronize_rcu();
1234         kfree(old_disk_conf);
1235         kfree(old_plan);
1236         goto success;
1237
1238 fail_unlock:
1239         mutex_unlock(&mdev->tconn->conf_update);
1240  fail:
1241         kfree(new_disk_conf);
1242         kfree(new_plan);
1243 success:
1244         put_ldev(mdev);
1245  out:
1246         drbd_adm_finish(info, retcode);
1247         return 0;
1248 }
1249
1250 int drbd_adm_attach(struct sk_buff *skb, struct genl_info *info)
1251 {
1252         struct drbd_conf *mdev;
1253         int err;
1254         enum drbd_ret_code retcode;
1255         enum determine_dev_size dd;
1256         sector_t max_possible_sectors;
1257         sector_t min_md_device_sectors;
1258         struct drbd_backing_dev *nbc = NULL; /* new_backing_conf */
1259         struct disk_conf *new_disk_conf = NULL;
1260         struct block_device *bdev;
1261         struct lru_cache *resync_lru = NULL;
1262         struct fifo_buffer *new_plan = NULL;
1263         union drbd_state ns, os;
1264         enum drbd_state_rv rv;
1265         struct net_conf *nc;
1266         int cp_discovered = 0;
1267
1268         retcode = drbd_adm_prepare(skb, info, DRBD_ADM_NEED_MINOR);
1269         if (!adm_ctx.reply_skb)
1270                 return retcode;
1271         if (retcode != NO_ERROR)
1272                 goto finish;
1273
1274         mdev = adm_ctx.mdev;
1275         conn_reconfig_start(mdev->tconn);
1276
1277         /* if you want to reconfigure, please tear down first */
1278         if (mdev->state.disk > D_DISKLESS) {
1279                 retcode = ERR_DISK_CONFIGURED;
1280                 goto fail;
1281         }
1282         /* It may just now have detached because of IO error.  Make sure
1283          * drbd_ldev_destroy is done already, we may end up here very fast,
1284          * e.g. if someone calls attach from the on-io-error handler,
1285          * to realize a "hot spare" feature (not that I'd recommend that) */
1286         wait_event(mdev->misc_wait, !atomic_read(&mdev->local_cnt));
1287
1288         /* allocation not in the IO path, drbdsetup context */
1289         nbc = kzalloc(sizeof(struct drbd_backing_dev), GFP_KERNEL);
1290         if (!nbc) {
1291                 retcode = ERR_NOMEM;
1292                 goto fail;
1293         }
1294         new_disk_conf = kzalloc(sizeof(struct disk_conf), GFP_KERNEL);
1295         if (!new_disk_conf) {
1296                 retcode = ERR_NOMEM;
1297                 goto fail;
1298         }
1299         nbc->disk_conf = new_disk_conf;
1300
1301         set_disk_conf_defaults(new_disk_conf);
1302         err = disk_conf_from_attrs(new_disk_conf, info);
1303         if (err) {
1304                 retcode = ERR_MANDATORY_TAG;
1305                 drbd_msg_put_info(from_attrs_err_to_txt(err));
1306                 goto fail;
1307         }
1308
1309         enforce_disk_conf_limits(new_disk_conf);
1310
1311         new_plan = fifo_alloc((new_disk_conf->c_plan_ahead * 10 * SLEEP_TIME) / HZ);
1312         if (!new_plan) {
1313                 retcode = ERR_NOMEM;
1314                 goto fail;
1315         }
1316
1317         if (new_disk_conf->meta_dev_idx < DRBD_MD_INDEX_FLEX_INT) {
1318                 retcode = ERR_MD_IDX_INVALID;
1319                 goto fail;
1320         }
1321
1322         rcu_read_lock();
1323         nc = rcu_dereference(mdev->tconn->net_conf);
1324         if (nc) {
1325                 if (new_disk_conf->fencing == FP_STONITH && nc->wire_protocol == DRBD_PROT_A) {
1326                         rcu_read_unlock();
1327                         retcode = ERR_STONITH_AND_PROT_A;
1328                         goto fail;
1329                 }
1330         }
1331         rcu_read_unlock();
1332
1333         bdev = blkdev_get_by_path(new_disk_conf->backing_dev,
1334                                   FMODE_READ | FMODE_WRITE | FMODE_EXCL, mdev);
1335         if (IS_ERR(bdev)) {
1336                 dev_err(DEV, "open(\"%s\") failed with %ld\n", new_disk_conf->backing_dev,
1337                         PTR_ERR(bdev));
1338                 retcode = ERR_OPEN_DISK;
1339                 goto fail;
1340         }
1341         nbc->backing_bdev = bdev;
1342
1343         /*
1344          * meta_dev_idx >= 0: external fixed size, possibly multiple
1345          * drbd sharing one meta device.  TODO in that case, paranoia
1346          * check that [md_bdev, meta_dev_idx] is not yet used by some
1347          * other drbd minor!  (if you use drbd.conf + drbdadm, that
1348          * should check it for you already; but if you don't, or
1349          * someone fooled it, we need to double check here)
1350          */
1351         bdev = blkdev_get_by_path(new_disk_conf->meta_dev,
1352                                   FMODE_READ | FMODE_WRITE | FMODE_EXCL,
1353                                   (new_disk_conf->meta_dev_idx < 0) ?
1354                                   (void *)mdev : (void *)drbd_m_holder);
1355         if (IS_ERR(bdev)) {
1356                 dev_err(DEV, "open(\"%s\") failed with %ld\n", new_disk_conf->meta_dev,
1357                         PTR_ERR(bdev));
1358                 retcode = ERR_OPEN_MD_DISK;
1359                 goto fail;
1360         }
1361         nbc->md_bdev = bdev;
1362
1363         if ((nbc->backing_bdev == nbc->md_bdev) !=
1364             (new_disk_conf->meta_dev_idx == DRBD_MD_INDEX_INTERNAL ||
1365              new_disk_conf->meta_dev_idx == DRBD_MD_INDEX_FLEX_INT)) {
1366                 retcode = ERR_MD_IDX_INVALID;
1367                 goto fail;
1368         }
1369
1370         resync_lru = lc_create("resync", drbd_bm_ext_cache,
1371                         1, 61, sizeof(struct bm_extent),
1372                         offsetof(struct bm_extent, lce));
1373         if (!resync_lru) {
1374                 retcode = ERR_NOMEM;
1375                 goto fail;
1376         }
1377
1378         /* RT - for drbd_get_max_capacity() DRBD_MD_INDEX_FLEX_INT */
1379         drbd_md_set_sector_offsets(mdev, nbc);
1380
1381         if (drbd_get_max_capacity(nbc) < new_disk_conf->disk_size) {
1382                 dev_err(DEV, "max capacity %llu smaller than disk size %llu\n",
1383                         (unsigned long long) drbd_get_max_capacity(nbc),
1384                         (unsigned long long) new_disk_conf->disk_size);
1385                 retcode = ERR_DISK_TOO_SMALL;
1386                 goto fail;
1387         }
1388
1389         if (new_disk_conf->meta_dev_idx < 0) {
1390                 max_possible_sectors = DRBD_MAX_SECTORS_FLEX;
1391                 /* at least one MB, otherwise it does not make sense */
1392                 min_md_device_sectors = (2<<10);
1393         } else {
1394                 max_possible_sectors = DRBD_MAX_SECTORS;
1395                 min_md_device_sectors = MD_RESERVED_SECT * (new_disk_conf->meta_dev_idx + 1);
1396         }
1397
1398         if (drbd_get_capacity(nbc->md_bdev) < min_md_device_sectors) {
1399                 retcode = ERR_MD_DISK_TOO_SMALL;
1400                 dev_warn(DEV, "refusing attach: md-device too small, "
1401                      "at least %llu sectors needed for this meta-disk type\n",
1402                      (unsigned long long) min_md_device_sectors);
1403                 goto fail;
1404         }
1405
1406         /* Make sure the new disk is big enough
1407          * (we may currently be R_PRIMARY with no local disk...) */
1408         if (drbd_get_max_capacity(nbc) <
1409             drbd_get_capacity(mdev->this_bdev)) {
1410                 retcode = ERR_DISK_TOO_SMALL;
1411                 goto fail;
1412         }
1413
1414         nbc->known_size = drbd_get_capacity(nbc->backing_bdev);
1415
1416         if (nbc->known_size > max_possible_sectors) {
1417                 dev_warn(DEV, "==> truncating very big lower level device "
1418                         "to currently maximum possible %llu sectors <==\n",
1419                         (unsigned long long) max_possible_sectors);
1420                 if (new_disk_conf->meta_dev_idx >= 0)
1421                         dev_warn(DEV, "==>> using internal or flexible "
1422                                       "meta data may help <<==\n");
1423         }
1424
1425         drbd_suspend_io(mdev);
1426         /* also wait for the last barrier ack. */
1427         wait_event(mdev->misc_wait, !atomic_read(&mdev->ap_pending_cnt) || drbd_suspended(mdev));
1428         /* and for any other previously queued work */
1429         drbd_flush_workqueue(mdev);
1430
1431         rv = _drbd_request_state(mdev, NS(disk, D_ATTACHING), CS_VERBOSE);
1432         retcode = rv;  /* FIXME: Type mismatch. */
1433         drbd_resume_io(mdev);
1434         if (rv < SS_SUCCESS)
1435                 goto fail;
1436
1437         if (!get_ldev_if_state(mdev, D_ATTACHING))
1438                 goto force_diskless;
1439
1440         drbd_md_set_sector_offsets(mdev, nbc);
1441
1442         if (!mdev->bitmap) {
1443                 if (drbd_bm_init(mdev)) {
1444                         retcode = ERR_NOMEM;
1445                         goto force_diskless_dec;
1446                 }
1447         }
1448
1449         retcode = drbd_md_read(mdev, nbc);
1450         if (retcode != NO_ERROR)
1451                 goto force_diskless_dec;
1452
1453         if (mdev->state.conn < C_CONNECTED &&
1454             mdev->state.role == R_PRIMARY &&
1455             (mdev->ed_uuid & ~((u64)1)) != (nbc->md.uuid[UI_CURRENT] & ~((u64)1))) {
1456                 dev_err(DEV, "Can only attach to data with current UUID=%016llX\n",
1457                     (unsigned long long)mdev->ed_uuid);
1458                 retcode = ERR_DATA_NOT_CURRENT;
1459                 goto force_diskless_dec;
1460         }
1461
1462         /* Since we are diskless, fix the activity log first... */
1463         if (drbd_check_al_size(mdev, new_disk_conf)) {
1464                 retcode = ERR_NOMEM;
1465                 goto force_diskless_dec;
1466         }
1467
1468         /* Prevent shrinking of consistent devices ! */
1469         if (drbd_md_test_flag(nbc, MDF_CONSISTENT) &&
1470             drbd_new_dev_size(mdev, nbc, nbc->disk_conf->disk_size, 0) < nbc->md.la_size_sect) {
1471                 dev_warn(DEV, "refusing to truncate a consistent device\n");
1472                 retcode = ERR_DISK_TOO_SMALL;
1473                 goto force_diskless_dec;
1474         }
1475
1476         if (!drbd_al_read_log(mdev, nbc)) {
1477                 retcode = ERR_IO_MD_DISK;
1478                 goto force_diskless_dec;
1479         }
1480
1481         /* Reset the "barriers don't work" bits here, then force meta data to
1482          * be written, to ensure we determine if barriers are supported. */
1483         if (new_disk_conf->md_flushes)
1484                 clear_bit(MD_NO_FUA, &mdev->flags);
1485         else
1486                 set_bit(MD_NO_FUA, &mdev->flags);
1487
1488         /* Point of no return reached.
1489          * Devices and memory are no longer released by error cleanup below.
1490          * now mdev takes over responsibility, and the state engine should
1491          * clean it up somewhere.  */
1492         D_ASSERT(mdev->ldev == NULL);
1493         mdev->ldev = nbc;
1494         mdev->resync = resync_lru;
1495         mdev->rs_plan_s = new_plan;
1496         nbc = NULL;
1497         resync_lru = NULL;
1498         new_disk_conf = NULL;
1499         new_plan = NULL;
1500
1501         mdev->write_ordering = WO_bdev_flush;
1502         drbd_bump_write_ordering(mdev, WO_bdev_flush);
1503
1504         if (drbd_md_test_flag(mdev->ldev, MDF_CRASHED_PRIMARY))
1505                 set_bit(CRASHED_PRIMARY, &mdev->flags);
1506         else
1507                 clear_bit(CRASHED_PRIMARY, &mdev->flags);
1508
1509         if (drbd_md_test_flag(mdev->ldev, MDF_PRIMARY_IND) &&
1510             !(mdev->state.role == R_PRIMARY && mdev->tconn->susp_nod)) {
1511                 set_bit(CRASHED_PRIMARY, &mdev->flags);
1512                 cp_discovered = 1;
1513         }
1514
1515         mdev->send_cnt = 0;
1516         mdev->recv_cnt = 0;
1517         mdev->read_cnt = 0;
1518         mdev->writ_cnt = 0;
1519
1520         drbd_reconsider_max_bio_size(mdev);
1521
1522         /* If I am currently not R_PRIMARY,
1523          * but meta data primary indicator is set,
1524          * I just now recover from a hard crash,
1525          * and have been R_PRIMARY before that crash.
1526          *
1527          * Now, if I had no connection before that crash
1528          * (have been degraded R_PRIMARY), chances are that
1529          * I won't find my peer now either.
1530          *
1531          * In that case, and _only_ in that case,
1532          * we use the degr-wfc-timeout instead of the default,
1533          * so we can automatically recover from a crash of a
1534          * degraded but active "cluster" after a certain timeout.
1535          */
1536         clear_bit(USE_DEGR_WFC_T, &mdev->flags);
1537         if (mdev->state.role != R_PRIMARY &&
1538              drbd_md_test_flag(mdev->ldev, MDF_PRIMARY_IND) &&
1539             !drbd_md_test_flag(mdev->ldev, MDF_CONNECTED_IND))
1540                 set_bit(USE_DEGR_WFC_T, &mdev->flags);
1541
1542         dd = drbd_determine_dev_size(mdev, 0);
1543         if (dd == dev_size_error) {
1544                 retcode = ERR_NOMEM_BITMAP;
1545                 goto force_diskless_dec;
1546         } else if (dd == grew)
1547                 set_bit(RESYNC_AFTER_NEG, &mdev->flags);
1548
1549         if (drbd_md_test_flag(mdev->ldev, MDF_FULL_SYNC)) {
1550                 dev_info(DEV, "Assuming that all blocks are out of sync "
1551                      "(aka FullSync)\n");
1552                 if (drbd_bitmap_io(mdev, &drbd_bmio_set_n_write,
1553                         "set_n_write from attaching", BM_LOCKED_MASK)) {
1554                         retcode = ERR_IO_MD_DISK;
1555                         goto force_diskless_dec;
1556                 }
1557         } else {
1558                 if (drbd_bitmap_io(mdev, &drbd_bm_read,
1559                         "read from attaching", BM_LOCKED_MASK)) {
1560                         retcode = ERR_IO_MD_DISK;
1561                         goto force_diskless_dec;
1562                 }
1563         }
1564
1565         if (cp_discovered) {
1566                 drbd_al_apply_to_bm(mdev);
1567                 if (drbd_bitmap_io(mdev, &drbd_bm_write,
1568                         "crashed primary apply AL", BM_LOCKED_MASK)) {
1569                         retcode = ERR_IO_MD_DISK;
1570                         goto force_diskless_dec;
1571                 }
1572         }
1573
1574         if (_drbd_bm_total_weight(mdev) == drbd_bm_bits(mdev))
1575                 drbd_suspend_al(mdev); /* IO is still suspended here... */
1576
1577         spin_lock_irq(&mdev->tconn->req_lock);
1578         os = drbd_read_state(mdev);
1579         ns = os;
1580         /* If MDF_CONSISTENT is not set go into inconsistent state,
1581            otherwise investigate MDF_WasUpToDate...
1582            If MDF_WAS_UP_TO_DATE is not set go into D_OUTDATED disk state,
1583            otherwise into D_CONSISTENT state.
1584         */
1585         if (drbd_md_test_flag(mdev->ldev, MDF_CONSISTENT)) {
1586                 if (drbd_md_test_flag(mdev->ldev, MDF_WAS_UP_TO_DATE))
1587                         ns.disk = D_CONSISTENT;
1588                 else
1589                         ns.disk = D_OUTDATED;
1590         } else {
1591                 ns.disk = D_INCONSISTENT;
1592         }
1593
1594         if (drbd_md_test_flag(mdev->ldev, MDF_PEER_OUT_DATED))
1595                 ns.pdsk = D_OUTDATED;
1596
1597         rcu_read_lock();
1598         if (ns.disk == D_CONSISTENT &&
1599             (ns.pdsk == D_OUTDATED || rcu_dereference(mdev->ldev->disk_conf)->fencing == FP_DONT_CARE))
1600                 ns.disk = D_UP_TO_DATE;
1601         rcu_read_unlock();
1602
1603         /* All tests on MDF_PRIMARY_IND, MDF_CONNECTED_IND,
1604            MDF_CONSISTENT and MDF_WAS_UP_TO_DATE must happen before
1605            this point, because drbd_request_state() modifies these
1606            flags. */
1607
1608         /* In case we are C_CONNECTED postpone any decision on the new disk
1609            state after the negotiation phase. */
1610         if (mdev->state.conn == C_CONNECTED) {
1611                 mdev->new_state_tmp.i = ns.i;
1612                 ns.i = os.i;
1613                 ns.disk = D_NEGOTIATING;
1614
1615                 /* We expect to receive up-to-date UUIDs soon.
1616                    To avoid a race in receive_state, free p_uuid while
1617                    holding req_lock. I.e. atomic with the state change */
1618                 kfree(mdev->p_uuid);
1619                 mdev->p_uuid = NULL;
1620         }
1621
1622         rv = _drbd_set_state(mdev, ns, CS_VERBOSE, NULL);
1623         spin_unlock_irq(&mdev->tconn->req_lock);
1624
1625         if (rv < SS_SUCCESS)
1626                 goto force_diskless_dec;
1627
1628         if (mdev->state.role == R_PRIMARY)
1629                 mdev->ldev->md.uuid[UI_CURRENT] |=  (u64)1;
1630         else
1631                 mdev->ldev->md.uuid[UI_CURRENT] &= ~(u64)1;
1632
1633         drbd_md_mark_dirty(mdev);
1634         drbd_md_sync(mdev);
1635
1636         kobject_uevent(&disk_to_dev(mdev->vdisk)->kobj, KOBJ_CHANGE);
1637         put_ldev(mdev);
1638         conn_reconfig_done(mdev->tconn);
1639         drbd_adm_finish(info, retcode);
1640         return 0;
1641
1642  force_diskless_dec:
1643         put_ldev(mdev);
1644  force_diskless:
1645         drbd_force_state(mdev, NS(disk, D_FAILED));
1646         drbd_md_sync(mdev);
1647  fail:
1648         conn_reconfig_done(mdev->tconn);
1649         if (nbc) {
1650                 if (nbc->backing_bdev)
1651                         blkdev_put(nbc->backing_bdev,
1652                                    FMODE_READ | FMODE_WRITE | FMODE_EXCL);
1653                 if (nbc->md_bdev)
1654                         blkdev_put(nbc->md_bdev,
1655                                    FMODE_READ | FMODE_WRITE | FMODE_EXCL);
1656                 kfree(nbc);
1657         }
1658         kfree(new_disk_conf);
1659         lc_destroy(resync_lru);
1660         kfree(new_plan);
1661
1662  finish:
1663         drbd_adm_finish(info, retcode);
1664         return 0;
1665 }
1666
1667 static int adm_detach(struct drbd_conf *mdev)
1668 {
1669         enum drbd_state_rv retcode;
1670         int ret;
1671         drbd_suspend_io(mdev); /* so no-one is stuck in drbd_al_begin_io */
1672         retcode = drbd_request_state(mdev, NS(disk, D_FAILED));
1673         /* D_FAILED will transition to DISKLESS. */
1674         ret = wait_event_interruptible(mdev->misc_wait,
1675                         mdev->state.disk != D_FAILED);
1676         drbd_resume_io(mdev);
1677         if ((int)retcode == (int)SS_IS_DISKLESS)
1678                 retcode = SS_NOTHING_TO_DO;
1679         if (ret)
1680                 retcode = ERR_INTR;
1681         return retcode;
1682 }
1683
1684 /* Detaching the disk is a process in multiple stages.  First we need to lock
1685  * out application IO, in-flight IO, IO stuck in drbd_al_begin_io.
1686  * Then we transition to D_DISKLESS, and wait for put_ldev() to return all
1687  * internal references as well.
1688  * Only then we have finally detached. */
1689 int drbd_adm_detach(struct sk_buff *skb, struct genl_info *info)
1690 {
1691         enum drbd_ret_code retcode;
1692
1693         retcode = drbd_adm_prepare(skb, info, DRBD_ADM_NEED_MINOR);
1694         if (!adm_ctx.reply_skb)
1695                 return retcode;
1696         if (retcode != NO_ERROR)
1697                 goto out;
1698
1699         retcode = adm_detach(adm_ctx.mdev);
1700 out:
1701         drbd_adm_finish(info, retcode);
1702         return 0;
1703 }
1704
1705 static bool conn_resync_running(struct drbd_tconn *tconn)
1706 {
1707         struct drbd_conf *mdev;
1708         bool rv = false;
1709         int vnr;
1710
1711         rcu_read_lock();
1712         idr_for_each_entry(&tconn->volumes, mdev, vnr) {
1713                 if (mdev->state.conn == C_SYNC_SOURCE ||
1714                     mdev->state.conn == C_SYNC_TARGET ||
1715                     mdev->state.conn == C_PAUSED_SYNC_S ||
1716                     mdev->state.conn == C_PAUSED_SYNC_T) {
1717                         rv = true;
1718                         break;
1719                 }
1720         }
1721         rcu_read_unlock();
1722
1723         return rv;
1724 }
1725
1726 static bool conn_ov_running(struct drbd_tconn *tconn)
1727 {
1728         struct drbd_conf *mdev;
1729         bool rv = false;
1730         int vnr;
1731
1732         rcu_read_lock();
1733         idr_for_each_entry(&tconn->volumes, mdev, vnr) {
1734                 if (mdev->state.conn == C_VERIFY_S ||
1735                     mdev->state.conn == C_VERIFY_T) {
1736                         rv = true;
1737                         break;
1738                 }
1739         }
1740         rcu_read_unlock();
1741
1742         return rv;
1743 }
1744
1745 static enum drbd_ret_code
1746 _check_net_options(struct drbd_tconn *tconn, struct net_conf *old_conf, struct net_conf *new_conf)
1747 {
1748         struct drbd_conf *mdev;
1749         int i;
1750
1751         if (old_conf && tconn->cstate == C_WF_REPORT_PARAMS && tconn->agreed_pro_version < 100) {
1752                 if (new_conf->wire_protocol != old_conf->wire_protocol)
1753                         return ERR_NEED_APV_100;
1754
1755                 if (new_conf->two_primaries != old_conf->two_primaries)
1756                         return ERR_NEED_APV_100;
1757
1758                 if (!new_conf->integrity_alg != !old_conf->integrity_alg)
1759                         return ERR_NEED_APV_100;
1760
1761                 if (strcmp(new_conf->integrity_alg, old_conf->integrity_alg))
1762                         return ERR_NEED_APV_100;
1763         }
1764
1765         if (!new_conf->two_primaries &&
1766             conn_highest_role(tconn) == R_PRIMARY &&
1767             conn_highest_peer(tconn) == R_PRIMARY)
1768                 return ERR_NEED_ALLOW_TWO_PRI;
1769
1770         if (new_conf->two_primaries &&
1771             (new_conf->wire_protocol != DRBD_PROT_C))
1772                 return ERR_NOT_PROTO_C;
1773
1774         idr_for_each_entry(&tconn->volumes, mdev, i) {
1775                 if (get_ldev(mdev)) {
1776                         enum drbd_fencing_p fp = rcu_dereference(mdev->ldev->disk_conf)->fencing;
1777                         put_ldev(mdev);
1778                         if (new_conf->wire_protocol == DRBD_PROT_A && fp == FP_STONITH)
1779                                 return ERR_STONITH_AND_PROT_A;
1780                 }
1781                 if (mdev->state.role == R_PRIMARY && new_conf->discard_my_data)
1782                         return ERR_DISCARD;
1783         }
1784
1785         if (new_conf->on_congestion != OC_BLOCK && new_conf->wire_protocol != DRBD_PROT_A)
1786                 return ERR_CONG_NOT_PROTO_A;
1787
1788         return NO_ERROR;
1789 }
1790
1791 static enum drbd_ret_code
1792 check_net_options(struct drbd_tconn *tconn, struct net_conf *new_conf)
1793 {
1794         static enum drbd_ret_code rv;
1795         struct drbd_conf *mdev;
1796         int i;
1797
1798         rcu_read_lock();
1799         rv = _check_net_options(tconn, rcu_dereference(tconn->net_conf), new_conf);
1800         rcu_read_unlock();
1801
1802         /* tconn->volumes protected by genl_lock() here */
1803         idr_for_each_entry(&tconn->volumes, mdev, i) {
1804                 if (!mdev->bitmap) {
1805                         if(drbd_bm_init(mdev))
1806                                 return ERR_NOMEM;
1807                 }
1808         }
1809
1810         return rv;
1811 }
1812
1813 struct crypto {
1814         struct crypto_hash *verify_tfm;
1815         struct crypto_hash *csums_tfm;
1816         struct crypto_hash *cram_hmac_tfm;
1817         struct crypto_hash *integrity_tfm;
1818         void *int_dig_in;
1819         void *int_dig_vv;
1820 };
1821
1822 static int
1823 alloc_hash(struct crypto_hash **tfm, char *tfm_name, int err_alg)
1824 {
1825         if (!tfm_name[0])
1826                 return NO_ERROR;
1827
1828         *tfm = crypto_alloc_hash(tfm_name, 0, CRYPTO_ALG_ASYNC);
1829         if (IS_ERR(*tfm)) {
1830                 *tfm = NULL;
1831                 return err_alg;
1832         }
1833
1834         return NO_ERROR;
1835 }
1836
1837 static enum drbd_ret_code
1838 alloc_crypto(struct crypto *crypto, struct net_conf *new_conf)
1839 {
1840         char hmac_name[CRYPTO_MAX_ALG_NAME];
1841         enum drbd_ret_code rv;
1842         int hash_size;
1843
1844         rv = alloc_hash(&crypto->csums_tfm, new_conf->csums_alg,
1845                        ERR_CSUMS_ALG);
1846         if (rv != NO_ERROR)
1847                 return rv;
1848         rv = alloc_hash(&crypto->verify_tfm, new_conf->verify_alg,
1849                        ERR_VERIFY_ALG);
1850         if (rv != NO_ERROR)
1851                 return rv;
1852         rv = alloc_hash(&crypto->integrity_tfm, new_conf->integrity_alg,
1853                        ERR_INTEGRITY_ALG);
1854         if (rv != NO_ERROR)
1855                 return rv;
1856         if (new_conf->cram_hmac_alg[0] != 0) {
1857                 snprintf(hmac_name, CRYPTO_MAX_ALG_NAME, "hmac(%s)",
1858                          new_conf->cram_hmac_alg);
1859
1860                 rv = alloc_hash(&crypto->cram_hmac_tfm, hmac_name,
1861                                ERR_AUTH_ALG);
1862         }
1863         if (crypto->integrity_tfm) {
1864                 hash_size = crypto_hash_digestsize(crypto->integrity_tfm);
1865                 crypto->int_dig_in = kmalloc(hash_size, GFP_KERNEL);
1866                 if (!crypto->int_dig_in)
1867                         return ERR_NOMEM;
1868                 crypto->int_dig_vv = kmalloc(hash_size, GFP_KERNEL);
1869                 if (!crypto->int_dig_vv)
1870                         return ERR_NOMEM;
1871         }
1872
1873         return rv;
1874 }
1875
1876 static void free_crypto(struct crypto *crypto)
1877 {
1878         kfree(crypto->int_dig_in);
1879         kfree(crypto->int_dig_vv);
1880         crypto_free_hash(crypto->cram_hmac_tfm);
1881         crypto_free_hash(crypto->integrity_tfm);
1882         crypto_free_hash(crypto->csums_tfm);
1883         crypto_free_hash(crypto->verify_tfm);
1884 }
1885
1886 int drbd_adm_net_opts(struct sk_buff *skb, struct genl_info *info)
1887 {
1888         enum drbd_ret_code retcode;
1889         struct drbd_tconn *tconn;
1890         struct net_conf *old_conf, *new_conf = NULL;
1891         int err;
1892         int ovr; /* online verify running */
1893         int rsr; /* re-sync running */
1894         struct crypto crypto = { };
1895
1896         retcode = drbd_adm_prepare(skb, info, DRBD_ADM_NEED_CONNECTION);
1897         if (!adm_ctx.reply_skb)
1898                 return retcode;
1899         if (retcode != NO_ERROR)
1900                 goto out;
1901
1902         tconn = adm_ctx.tconn;
1903
1904         new_conf = kzalloc(sizeof(struct net_conf), GFP_KERNEL);
1905         if (!new_conf) {
1906                 retcode = ERR_NOMEM;
1907                 goto out;
1908         }
1909
1910         conn_reconfig_start(tconn);
1911
1912         mutex_lock(&tconn->data.mutex);
1913         mutex_lock(&tconn->conf_update);
1914         old_conf = tconn->net_conf;
1915
1916         if (!old_conf) {
1917                 drbd_msg_put_info("net conf missing, try connect");
1918                 retcode = ERR_INVALID_REQUEST;
1919                 goto fail;
1920         }
1921
1922         *new_conf = *old_conf;
1923         if (should_set_defaults(info))
1924                 set_net_conf_defaults(new_conf);
1925
1926         err = net_conf_from_attrs_for_change(new_conf, info);
1927         if (err && err != -ENOMSG) {
1928                 retcode = ERR_MANDATORY_TAG;
1929                 drbd_msg_put_info(from_attrs_err_to_txt(err));
1930                 goto fail;
1931         }
1932
1933         retcode = check_net_options(tconn, new_conf);
1934         if (retcode != NO_ERROR)
1935                 goto fail;
1936
1937         /* re-sync running */
1938         rsr = conn_resync_running(tconn);
1939         if (rsr && strcmp(new_conf->csums_alg, old_conf->csums_alg)) {
1940                 retcode = ERR_CSUMS_RESYNC_RUNNING;
1941                 goto fail;
1942         }
1943
1944         /* online verify running */
1945         ovr = conn_ov_running(tconn);
1946         if (ovr && strcmp(new_conf->verify_alg, old_conf->verify_alg)) {
1947                 retcode = ERR_VERIFY_RUNNING;
1948                 goto fail;
1949         }
1950
1951         retcode = alloc_crypto(&crypto, new_conf);
1952         if (retcode != NO_ERROR)
1953                 goto fail;
1954
1955         rcu_assign_pointer(tconn->net_conf, new_conf);
1956
1957         if (!rsr) {
1958                 crypto_free_hash(tconn->csums_tfm);
1959                 tconn->csums_tfm = crypto.csums_tfm;
1960                 crypto.csums_tfm = NULL;
1961         }
1962         if (!ovr) {
1963                 crypto_free_hash(tconn->verify_tfm);
1964                 tconn->verify_tfm = crypto.verify_tfm;
1965                 crypto.verify_tfm = NULL;
1966         }
1967
1968         kfree(tconn->int_dig_in);
1969         tconn->int_dig_in = crypto.int_dig_in;
1970         kfree(tconn->int_dig_vv);
1971         tconn->int_dig_vv = crypto.int_dig_vv;
1972         crypto_free_hash(tconn->integrity_tfm);
1973         tconn->integrity_tfm = crypto.integrity_tfm;
1974         if (tconn->cstate >= C_WF_REPORT_PARAMS && tconn->agreed_pro_version >= 100)
1975                 /* Do this without trying to take tconn->data.mutex again.  */
1976                 __drbd_send_protocol(tconn, P_PROTOCOL_UPDATE);
1977
1978         crypto_free_hash(tconn->cram_hmac_tfm);
1979         tconn->cram_hmac_tfm = crypto.cram_hmac_tfm;
1980
1981         mutex_unlock(&tconn->conf_update);
1982         mutex_unlock(&tconn->data.mutex);
1983         synchronize_rcu();
1984         kfree(old_conf);
1985
1986         if (tconn->cstate >= C_WF_REPORT_PARAMS)
1987                 drbd_send_sync_param(minor_to_mdev(conn_lowest_minor(tconn)));
1988
1989         goto done;
1990
1991  fail:
1992         mutex_unlock(&tconn->conf_update);
1993         mutex_unlock(&tconn->data.mutex);
1994         free_crypto(&crypto);
1995         kfree(new_conf);
1996  done:
1997         conn_reconfig_done(tconn);
1998  out:
1999         drbd_adm_finish(info, retcode);
2000         return 0;
2001 }
2002
2003 int drbd_adm_connect(struct sk_buff *skb, struct genl_info *info)
2004 {
2005         struct drbd_conf *mdev;
2006         struct net_conf *old_conf, *new_conf = NULL;
2007         struct crypto crypto = { };
2008         struct drbd_tconn *tconn;
2009         enum drbd_ret_code retcode;
2010         int i;
2011         int err;
2012
2013         retcode = drbd_adm_prepare(skb, info, DRBD_ADM_NEED_RESOURCE);
2014
2015         if (!adm_ctx.reply_skb)
2016                 return retcode;
2017         if (retcode != NO_ERROR)
2018                 goto out;
2019         if (!(adm_ctx.my_addr && adm_ctx.peer_addr)) {
2020                 drbd_msg_put_info("connection endpoint(s) missing");
2021                 retcode = ERR_INVALID_REQUEST;
2022                 goto out;
2023         }
2024
2025         /* No need for _rcu here. All reconfiguration is
2026          * strictly serialized on genl_lock(). We are protected against
2027          * concurrent reconfiguration/addition/deletion */
2028         list_for_each_entry(tconn, &drbd_tconns, all_tconn) {
2029                 if (nla_len(adm_ctx.my_addr) == tconn->my_addr_len &&
2030                     !memcmp(nla_data(adm_ctx.my_addr), &tconn->my_addr, tconn->my_addr_len)) {
2031                         retcode = ERR_LOCAL_ADDR;
2032                         goto out;
2033                 }
2034
2035                 if (nla_len(adm_ctx.peer_addr) == tconn->peer_addr_len &&
2036                     !memcmp(nla_data(adm_ctx.peer_addr), &tconn->peer_addr, tconn->peer_addr_len)) {
2037                         retcode = ERR_PEER_ADDR;
2038                         goto out;
2039                 }
2040         }
2041
2042         tconn = adm_ctx.tconn;
2043         conn_reconfig_start(tconn);
2044
2045         if (tconn->cstate > C_STANDALONE) {
2046                 retcode = ERR_NET_CONFIGURED;
2047                 goto fail;
2048         }
2049
2050         /* allocation not in the IO path, cqueue thread context */
2051         new_conf = kzalloc(sizeof(*new_conf), GFP_KERNEL);
2052         if (!new_conf) {
2053                 retcode = ERR_NOMEM;
2054                 goto fail;
2055         }
2056
2057         set_net_conf_defaults(new_conf);
2058
2059         err = net_conf_from_attrs(new_conf, info);
2060         if (err) {
2061                 retcode = ERR_MANDATORY_TAG;
2062                 drbd_msg_put_info(from_attrs_err_to_txt(err));
2063                 goto fail;
2064         }
2065
2066         retcode = check_net_options(tconn, new_conf);
2067         if (retcode != NO_ERROR)
2068                 goto fail;
2069
2070         retcode = alloc_crypto(&crypto, new_conf);
2071         if (retcode != NO_ERROR)
2072                 goto fail;
2073
2074         ((char *)new_conf->shared_secret)[SHARED_SECRET_MAX-1] = 0;
2075
2076         conn_flush_workqueue(tconn);
2077
2078         mutex_lock(&tconn->conf_update);
2079         old_conf = tconn->net_conf;
2080         if (old_conf) {
2081                 retcode = ERR_NET_CONFIGURED;
2082                 mutex_unlock(&tconn->conf_update);
2083                 goto fail;
2084         }
2085         rcu_assign_pointer(tconn->net_conf, new_conf);
2086
2087         conn_free_crypto(tconn);
2088         tconn->int_dig_in = crypto.int_dig_in;
2089         tconn->int_dig_vv = crypto.int_dig_vv;
2090         tconn->cram_hmac_tfm = crypto.cram_hmac_tfm;
2091         tconn->integrity_tfm = crypto.integrity_tfm;
2092         tconn->csums_tfm = crypto.csums_tfm;
2093         tconn->verify_tfm = crypto.verify_tfm;
2094
2095         tconn->my_addr_len = nla_len(adm_ctx.my_addr);
2096         memcpy(&tconn->my_addr, nla_data(adm_ctx.my_addr), tconn->my_addr_len);
2097         tconn->peer_addr_len = nla_len(adm_ctx.peer_addr);
2098         memcpy(&tconn->peer_addr, nla_data(adm_ctx.peer_addr), tconn->peer_addr_len);
2099
2100         mutex_unlock(&tconn->conf_update);
2101
2102         rcu_read_lock();
2103         idr_for_each_entry(&tconn->volumes, mdev, i) {
2104                 mdev->send_cnt = 0;
2105                 mdev->recv_cnt = 0;
2106         }
2107         rcu_read_unlock();
2108
2109         retcode = conn_request_state(tconn, NS(conn, C_UNCONNECTED), CS_VERBOSE);
2110
2111         conn_reconfig_done(tconn);
2112         drbd_adm_finish(info, retcode);
2113         return 0;
2114
2115 fail:
2116         free_crypto(&crypto);
2117         kfree(new_conf);
2118
2119         conn_reconfig_done(tconn);
2120 out:
2121         drbd_adm_finish(info, retcode);
2122         return 0;
2123 }
2124
2125 static enum drbd_state_rv conn_try_disconnect(struct drbd_tconn *tconn, bool force)
2126 {
2127         enum drbd_state_rv rv;
2128
2129         rv = conn_request_state(tconn, NS(conn, C_DISCONNECTING),
2130                         force ? CS_HARD : 0);
2131
2132         switch (rv) {
2133         case SS_NOTHING_TO_DO:
2134                 break;
2135         case SS_ALREADY_STANDALONE:
2136                 return SS_SUCCESS;
2137         case SS_PRIMARY_NOP:
2138                 /* Our state checking code wants to see the peer outdated. */
2139                 rv = conn_request_state(tconn, NS2(conn, C_DISCONNECTING,
2140                                                 pdsk, D_OUTDATED), CS_VERBOSE);
2141                 break;
2142         case SS_CW_FAILED_BY_PEER:
2143                 /* The peer probably wants to see us outdated. */
2144                 rv = conn_request_state(tconn, NS2(conn, C_DISCONNECTING,
2145                                                         disk, D_OUTDATED), 0);
2146                 if (rv == SS_IS_DISKLESS || rv == SS_LOWER_THAN_OUTDATED) {
2147                         rv = conn_request_state(tconn, NS(conn, C_DISCONNECTING),
2148                                         CS_HARD);
2149                 }
2150                 break;
2151         default:;
2152                 /* no special handling necessary */
2153         }
2154
2155         if (rv >= SS_SUCCESS) {
2156                 enum drbd_state_rv rv2;
2157                 /* No one else can reconfigure the network while I am here.
2158                  * The state handling only uses drbd_thread_stop_nowait(),
2159                  * we want to really wait here until the receiver is no more.
2160                  */
2161                 drbd_thread_stop(&adm_ctx.tconn->receiver);
2162
2163                 /* Race breaker.  This additional state change request may be
2164                  * necessary, if this was a forced disconnect during a receiver
2165                  * restart.  We may have "killed" the receiver thread just
2166                  * after drbdd_init() returned.  Typically, we should be
2167                  * C_STANDALONE already, now, and this becomes a no-op.
2168                  */
2169                 rv2 = conn_request_state(tconn, NS(conn, C_STANDALONE),
2170                                 CS_VERBOSE | CS_HARD);
2171                 if (rv2 < SS_SUCCESS)
2172                         conn_err(tconn,
2173                                 "unexpected rv2=%d in conn_try_disconnect()\n",
2174                                 rv2);
2175         }
2176         return rv;
2177 }
2178
2179 int drbd_adm_disconnect(struct sk_buff *skb, struct genl_info *info)
2180 {
2181         struct disconnect_parms parms;
2182         struct drbd_tconn *tconn;
2183         enum drbd_state_rv rv;
2184         enum drbd_ret_code retcode;
2185         int err;
2186
2187         retcode = drbd_adm_prepare(skb, info, DRBD_ADM_NEED_CONNECTION);
2188         if (!adm_ctx.reply_skb)
2189                 return retcode;
2190         if (retcode != NO_ERROR)
2191                 goto fail;
2192
2193         tconn = adm_ctx.tconn;
2194         memset(&parms, 0, sizeof(parms));
2195         if (info->attrs[DRBD_NLA_DISCONNECT_PARMS]) {
2196                 err = disconnect_parms_from_attrs(&parms, info);
2197                 if (err) {
2198                         retcode = ERR_MANDATORY_TAG;
2199                         drbd_msg_put_info(from_attrs_err_to_txt(err));
2200                         goto fail;
2201                 }
2202         }
2203
2204         rv = conn_try_disconnect(tconn, parms.force_disconnect);
2205         if (rv < SS_SUCCESS)
2206                 retcode = rv;  /* FIXME: Type mismatch. */
2207         else
2208                 retcode = NO_ERROR;
2209  fail:
2210         drbd_adm_finish(info, retcode);
2211         return 0;
2212 }
2213
2214 void resync_after_online_grow(struct drbd_conf *mdev)
2215 {
2216         int iass; /* I am sync source */
2217
2218         dev_info(DEV, "Resync of new storage after online grow\n");
2219         if (mdev->state.role != mdev->state.peer)
2220                 iass = (mdev->state.role == R_PRIMARY);
2221         else
2222                 iass = test_bit(DISCARD_CONCURRENT, &mdev->tconn->flags);
2223
2224         if (iass)
2225                 drbd_start_resync(mdev, C_SYNC_SOURCE);
2226         else
2227                 _drbd_request_state(mdev, NS(conn, C_WF_SYNC_UUID), CS_VERBOSE + CS_SERIALIZE);
2228 }
2229
2230 int drbd_adm_resize(struct sk_buff *skb, struct genl_info *info)
2231 {
2232         struct disk_conf *old_disk_conf, *new_disk_conf = NULL;
2233         struct resize_parms rs;
2234         struct drbd_conf *mdev;
2235         enum drbd_ret_code retcode;
2236         enum determine_dev_size dd;
2237         enum dds_flags ddsf;
2238         sector_t u_size;
2239         int err;
2240
2241         retcode = drbd_adm_prepare(skb, info, DRBD_ADM_NEED_MINOR);
2242         if (!adm_ctx.reply_skb)
2243                 return retcode;
2244         if (retcode != NO_ERROR)
2245                 goto fail;
2246
2247         memset(&rs, 0, sizeof(struct resize_parms));
2248         if (info->attrs[DRBD_NLA_RESIZE_PARMS]) {
2249                 err = resize_parms_from_attrs(&rs, info);
2250                 if (err) {
2251                         retcode = ERR_MANDATORY_TAG;
2252                         drbd_msg_put_info(from_attrs_err_to_txt(err));
2253                         goto fail;
2254                 }
2255         }
2256
2257         mdev = adm_ctx.mdev;
2258         if (mdev->state.conn > C_CONNECTED) {
2259                 retcode = ERR_RESIZE_RESYNC;
2260                 goto fail;
2261         }
2262
2263         if (mdev->state.role == R_SECONDARY &&
2264             mdev->state.peer == R_SECONDARY) {
2265                 retcode = ERR_NO_PRIMARY;
2266                 goto fail;
2267         }
2268
2269         if (!get_ldev(mdev)) {
2270                 retcode = ERR_NO_DISK;
2271                 goto fail;
2272         }
2273
2274         if (rs.no_resync && mdev->tconn->agreed_pro_version < 93) {
2275                 retcode = ERR_NEED_APV_93;
2276                 goto fail;
2277         }
2278
2279         rcu_read_lock();
2280         u_size = rcu_dereference(mdev->ldev->disk_conf)->disk_size;
2281         rcu_read_unlock();
2282         if (u_size != (sector_t)rs.resize_size) {
2283                 new_disk_conf = kmalloc(sizeof(struct disk_conf), GFP_KERNEL);
2284                 if (!new_disk_conf) {
2285                         retcode = ERR_NOMEM;
2286                         goto fail;
2287                 }
2288         }
2289
2290         if (mdev->ldev->known_size != drbd_get_capacity(mdev->ldev->backing_bdev))
2291                 mdev->ldev->known_size = drbd_get_capacity(mdev->ldev->backing_bdev);
2292
2293         if (new_disk_conf) {
2294                 mutex_lock(&mdev->tconn->conf_update);
2295                 old_disk_conf = mdev->ldev->disk_conf;
2296                 *new_disk_conf = *old_disk_conf;
2297                 new_disk_conf->disk_size = (sector_t)rs.resize_size;
2298                 rcu_assign_pointer(mdev->ldev->disk_conf, new_disk_conf);
2299                 mutex_unlock(&mdev->tconn->conf_update);
2300                 synchronize_rcu();
2301                 kfree(old_disk_conf);
2302         }
2303
2304         ddsf = (rs.resize_force ? DDSF_FORCED : 0) | (rs.no_resync ? DDSF_NO_RESYNC : 0);
2305         dd = drbd_determine_dev_size(mdev, ddsf);
2306         drbd_md_sync(mdev);
2307         put_ldev(mdev);
2308         if (dd == dev_size_error) {
2309                 retcode = ERR_NOMEM_BITMAP;
2310                 goto fail;
2311         }
2312
2313         if (mdev->state.conn == C_CONNECTED) {
2314                 if (dd == grew)
2315                         set_bit(RESIZE_PENDING, &mdev->flags);
2316
2317                 drbd_send_uuids(mdev);
2318                 drbd_send_sizes(mdev, 1, ddsf);
2319         }
2320
2321  fail:
2322         drbd_adm_finish(info, retcode);
2323         return 0;
2324 }
2325
2326 int drbd_adm_resource_opts(struct sk_buff *skb, struct genl_info *info)
2327 {
2328         enum drbd_ret_code retcode;
2329         struct drbd_tconn *tconn;
2330         struct res_opts res_opts;
2331         int err;
2332
2333         retcode = drbd_adm_prepare(skb, info, DRBD_ADM_NEED_RESOURCE);
2334         if (!adm_ctx.reply_skb)
2335                 return retcode;
2336         if (retcode != NO_ERROR)
2337                 goto fail;
2338         tconn = adm_ctx.tconn;
2339
2340         res_opts = tconn->res_opts;
2341         if (should_set_defaults(info))
2342                 set_res_opts_defaults(&res_opts);
2343
2344         err = res_opts_from_attrs(&res_opts, info);
2345         if (err && err != -ENOMSG) {
2346                 retcode = ERR_MANDATORY_TAG;
2347                 drbd_msg_put_info(from_attrs_err_to_txt(err));
2348                 goto fail;
2349         }
2350
2351         err = set_resource_options(tconn, &res_opts);
2352         if (err) {
2353                 retcode = ERR_INVALID_REQUEST;
2354                 if (err == -ENOMEM)
2355                         retcode = ERR_NOMEM;
2356         }
2357
2358 fail:
2359         drbd_adm_finish(info, retcode);
2360         return 0;
2361 }
2362
2363 int drbd_adm_invalidate(struct sk_buff *skb, struct genl_info *info)
2364 {
2365         struct drbd_conf *mdev;
2366         int retcode; /* enum drbd_ret_code rsp. enum drbd_state_rv */
2367
2368         retcode = drbd_adm_prepare(skb, info, DRBD_ADM_NEED_MINOR);
2369         if (!adm_ctx.reply_skb)
2370                 return retcode;
2371         if (retcode != NO_ERROR)
2372                 goto out;
2373
2374         mdev = adm_ctx.mdev;
2375
2376         /* If there is still bitmap IO pending, probably because of a previous
2377          * resync just being finished, wait for it before requesting a new resync. */
2378         wait_event(mdev->misc_wait, !test_bit(BITMAP_IO, &mdev->flags));
2379
2380         retcode = _drbd_request_state(mdev, NS(conn, C_STARTING_SYNC_T), CS_ORDERED);
2381
2382         if (retcode < SS_SUCCESS && retcode != SS_NEED_CONNECTION)
2383                 retcode = drbd_request_state(mdev, NS(conn, C_STARTING_SYNC_T));
2384
2385         while (retcode == SS_NEED_CONNECTION) {
2386                 spin_lock_irq(&mdev->tconn->req_lock);
2387                 if (mdev->state.conn < C_CONNECTED)
2388                         retcode = _drbd_set_state(_NS(mdev, disk, D_INCONSISTENT), CS_VERBOSE, NULL);
2389                 spin_unlock_irq(&mdev->tconn->req_lock);
2390
2391                 if (retcode != SS_NEED_CONNECTION)
2392                         break;
2393
2394                 retcode = drbd_request_state(mdev, NS(conn, C_STARTING_SYNC_T));
2395         }
2396
2397 out:
2398         drbd_adm_finish(info, retcode);
2399         return 0;
2400 }
2401
2402 static int drbd_bmio_set_susp_al(struct drbd_conf *mdev)
2403 {
2404         int rv;
2405
2406         rv = drbd_bmio_set_n_write(mdev);
2407         drbd_suspend_al(mdev);
2408         return rv;
2409 }
2410
2411 static int drbd_adm_simple_request_state(struct sk_buff *skb, struct genl_info *info,
2412                 union drbd_state mask, union drbd_state val)
2413 {
2414         enum drbd_ret_code retcode;
2415
2416         retcode = drbd_adm_prepare(skb, info, DRBD_ADM_NEED_MINOR);
2417         if (!adm_ctx.reply_skb)
2418                 return retcode;
2419         if (retcode != NO_ERROR)
2420                 goto out;
2421
2422         retcode = drbd_request_state(adm_ctx.mdev, mask, val);
2423 out:
2424         drbd_adm_finish(info, retcode);
2425         return 0;
2426 }
2427
2428 int drbd_adm_invalidate_peer(struct sk_buff *skb, struct genl_info *info)
2429 {
2430         return drbd_adm_simple_request_state(skb, info, NS(conn, C_STARTING_SYNC_S));
2431 }
2432
2433 int drbd_adm_pause_sync(struct sk_buff *skb, struct genl_info *info)
2434 {
2435         enum drbd_ret_code retcode;
2436
2437         retcode = drbd_adm_prepare(skb, info, DRBD_ADM_NEED_MINOR);
2438         if (!adm_ctx.reply_skb)
2439                 return retcode;
2440         if (retcode != NO_ERROR)
2441                 goto out;
2442
2443         if (drbd_request_state(adm_ctx.mdev, NS(user_isp, 1)) == SS_NOTHING_TO_DO)
2444                 retcode = ERR_PAUSE_IS_SET;
2445 out:
2446         drbd_adm_finish(info, retcode);
2447         return 0;
2448 }
2449
2450 int drbd_adm_resume_sync(struct sk_buff *skb, struct genl_info *info)
2451 {
2452         union drbd_dev_state s;
2453         enum drbd_ret_code retcode;
2454
2455         retcode = drbd_adm_prepare(skb, info, DRBD_ADM_NEED_MINOR);
2456         if (!adm_ctx.reply_skb)
2457                 return retcode;
2458         if (retcode != NO_ERROR)
2459                 goto out;
2460
2461         if (drbd_request_state(adm_ctx.mdev, NS(user_isp, 0)) == SS_NOTHING_TO_DO) {
2462                 s = adm_ctx.mdev->state;
2463                 if (s.conn == C_PAUSED_SYNC_S || s.conn == C_PAUSED_SYNC_T) {
2464                         retcode = s.aftr_isp ? ERR_PIC_AFTER_DEP :
2465                                   s.peer_isp ? ERR_PIC_PEER_DEP : ERR_PAUSE_IS_CLEAR;
2466                 } else {
2467                         retcode = ERR_PAUSE_IS_CLEAR;
2468                 }
2469         }
2470
2471 out:
2472         drbd_adm_finish(info, retcode);
2473         return 0;
2474 }
2475
2476 int drbd_adm_suspend_io(struct sk_buff *skb, struct genl_info *info)
2477 {
2478         return drbd_adm_simple_request_state(skb, info, NS(susp, 1));
2479 }
2480
2481 int drbd_adm_resume_io(struct sk_buff *skb, struct genl_info *info)
2482 {
2483         struct drbd_conf *mdev;
2484         int retcode; /* enum drbd_ret_code rsp. enum drbd_state_rv */
2485
2486         retcode = drbd_adm_prepare(skb, info, DRBD_ADM_NEED_MINOR);
2487         if (!adm_ctx.reply_skb)
2488                 return retcode;
2489         if (retcode != NO_ERROR)
2490                 goto out;
2491
2492         mdev = adm_ctx.mdev;
2493         if (test_bit(NEW_CUR_UUID, &mdev->flags)) {
2494                 drbd_uuid_new_current(mdev);
2495                 clear_bit(NEW_CUR_UUID, &mdev->flags);
2496         }
2497         drbd_suspend_io(mdev);
2498         retcode = drbd_request_state(mdev, NS3(susp, 0, susp_nod, 0, susp_fen, 0));
2499         if (retcode == SS_SUCCESS) {
2500                 if (mdev->state.conn < C_CONNECTED)
2501                         tl_clear(mdev->tconn);
2502                 if (mdev->state.disk == D_DISKLESS || mdev->state.disk == D_FAILED)
2503                         tl_restart(mdev->tconn, FAIL_FROZEN_DISK_IO);
2504         }
2505         drbd_resume_io(mdev);
2506
2507 out:
2508         drbd_adm_finish(info, retcode);
2509         return 0;
2510 }
2511
2512 int drbd_adm_outdate(struct sk_buff *skb, struct genl_info *info)
2513 {
2514         return drbd_adm_simple_request_state(skb, info, NS(disk, D_OUTDATED));
2515 }
2516
2517 int nla_put_drbd_cfg_context(struct sk_buff *skb, struct drbd_tconn *tconn, unsigned vnr)
2518 {
2519         struct nlattr *nla;
2520         nla = nla_nest_start(skb, DRBD_NLA_CFG_CONTEXT);
2521         if (!nla)
2522                 goto nla_put_failure;
2523         if (vnr != VOLUME_UNSPECIFIED)
2524                 NLA_PUT_U32(skb, T_ctx_volume, vnr);
2525         NLA_PUT_STRING(skb, T_ctx_resource_name, tconn->name);
2526         if (tconn->my_addr_len)
2527                 NLA_PUT(skb, T_ctx_my_addr, tconn->my_addr_len, &tconn->my_addr);
2528         if (tconn->peer_addr_len)
2529                 NLA_PUT(skb, T_ctx_peer_addr, tconn->peer_addr_len, &tconn->peer_addr);
2530         nla_nest_end(skb, nla);
2531         return 0;
2532
2533 nla_put_failure:
2534         if (nla)
2535                 nla_nest_cancel(skb, nla);
2536         return -EMSGSIZE;
2537 }
2538
2539 int nla_put_status_info(struct sk_buff *skb, struct drbd_conf *mdev,
2540                 const struct sib_info *sib)
2541 {
2542         struct state_info *si = NULL; /* for sizeof(si->member); */
2543         struct net_conf *nc;
2544         struct nlattr *nla;
2545         int got_ldev;
2546         int err = 0;
2547         int exclude_sensitive;
2548
2549         /* If sib != NULL, this is drbd_bcast_event, which anyone can listen
2550          * to.  So we better exclude_sensitive information.
2551          *
2552          * If sib == NULL, this is drbd_adm_get_status, executed synchronously
2553          * in the context of the requesting user process. Exclude sensitive
2554          * information, unless current has superuser.
2555          *
2556          * NOTE: for drbd_adm_get_status_all(), this is a netlink dump, and
2557          * relies on the current implementation of netlink_dump(), which
2558          * executes the dump callback successively from netlink_recvmsg(),
2559          * always in the context of the receiving process */
2560         exclude_sensitive = sib || !capable(CAP_SYS_ADMIN);
2561
2562         got_ldev = get_ldev(mdev);
2563
2564         /* We need to add connection name and volume number information still.
2565          * Minor number is in drbd_genlmsghdr. */
2566         if (nla_put_drbd_cfg_context(skb, mdev->tconn, mdev->vnr))
2567                 goto nla_put_failure;
2568
2569         if (res_opts_to_skb(skb, &mdev->tconn->res_opts, exclude_sensitive))
2570                 goto nla_put_failure;
2571
2572         rcu_read_lock();
2573         if (got_ldev)
2574                 if (disk_conf_to_skb(skb, rcu_dereference(mdev->ldev->disk_conf), exclude_sensitive))
2575                         goto nla_put_failure;
2576
2577         nc = rcu_dereference(mdev->tconn->net_conf);
2578         if (nc)
2579                 err = net_conf_to_skb(skb, nc, exclude_sensitive);
2580         rcu_read_unlock();
2581         if (err)
2582                 goto nla_put_failure;
2583
2584         nla = nla_nest_start(skb, DRBD_NLA_STATE_INFO);
2585         if (!nla)
2586                 goto nla_put_failure;
2587         NLA_PUT_U32(skb, T_sib_reason, sib ? sib->sib_reason : SIB_GET_STATUS_REPLY);
2588         NLA_PUT_U32(skb, T_current_state, mdev->state.i);
2589         NLA_PUT_U64(skb, T_ed_uuid, mdev->ed_uuid);
2590         NLA_PUT_U64(skb, T_capacity, drbd_get_capacity(mdev->this_bdev));
2591
2592         if (got_ldev) {
2593                 NLA_PUT_U32(skb, T_disk_flags, mdev->ldev->md.flags);
2594                 NLA_PUT(skb, T_uuids, sizeof(si->uuids), mdev->ldev->md.uuid);
2595                 NLA_PUT_U64(skb, T_bits_total, drbd_bm_bits(mdev));
2596                 NLA_PUT_U64(skb, T_bits_oos, drbd_bm_total_weight(mdev));
2597                 if (C_SYNC_SOURCE <= mdev->state.conn &&
2598                     C_PAUSED_SYNC_T >= mdev->state.conn) {
2599                         NLA_PUT_U64(skb, T_bits_rs_total, mdev->rs_total);
2600                         NLA_PUT_U64(skb, T_bits_rs_failed, mdev->rs_failed);
2601                 }
2602         }
2603
2604         if (sib) {
2605                 switch(sib->sib_reason) {
2606                 case SIB_SYNC_PROGRESS:
2607                 case SIB_GET_STATUS_REPLY:
2608                         break;
2609                 case SIB_STATE_CHANGE:
2610                         NLA_PUT_U32(skb, T_prev_state, sib->os.i);
2611                         NLA_PUT_U32(skb, T_new_state, sib->ns.i);
2612                         break;
2613                 case SIB_HELPER_POST:
2614                         NLA_PUT_U32(skb,
2615                                 T_helper_exit_code, sib->helper_exit_code);
2616                         /* fall through */
2617                 case SIB_HELPER_PRE:
2618                         NLA_PUT_STRING(skb, T_helper, sib->helper_name);
2619                         break;
2620                 }
2621         }
2622         nla_nest_end(skb, nla);
2623
2624         if (0)
2625 nla_put_failure:
2626                 err = -EMSGSIZE;
2627         if (got_ldev)
2628                 put_ldev(mdev);
2629         return err;
2630 }
2631
2632 int drbd_adm_get_status(struct sk_buff *skb, struct genl_info *info)
2633 {
2634         enum drbd_ret_code retcode;
2635         int err;
2636
2637         retcode = drbd_adm_prepare(skb, info, DRBD_ADM_NEED_MINOR);
2638         if (!adm_ctx.reply_skb)
2639                 return retcode;
2640         if (retcode != NO_ERROR)
2641                 goto out;
2642
2643         err = nla_put_status_info(adm_ctx.reply_skb, adm_ctx.mdev, NULL);
2644         if (err) {
2645                 nlmsg_free(adm_ctx.reply_skb);
2646                 return err;
2647         }
2648 out:
2649         drbd_adm_finish(info, retcode);
2650         return 0;
2651 }
2652
2653 int get_one_status(struct sk_buff *skb, struct netlink_callback *cb)
2654 {
2655         struct drbd_conf *mdev;
2656         struct drbd_genlmsghdr *dh;
2657         struct drbd_tconn *pos = (struct drbd_tconn*)cb->args[0];
2658         struct drbd_tconn *tconn = NULL;
2659         struct drbd_tconn *tmp;
2660         unsigned volume = cb->args[1];
2661
2662         /* Open coded, deferred, iteration:
2663          * list_for_each_entry_safe(tconn, tmp, &drbd_tconns, all_tconn) {
2664          *      idr_for_each_entry(&tconn->volumes, mdev, i) {
2665          *        ...
2666          *      }
2667          * }
2668          * where tconn is cb->args[0];
2669          * and i is cb->args[1];
2670          *
2671          * cb->args[2] indicates if we shall loop over all resources,
2672          * or just dump all volumes of a single resource.
2673          *
2674          * This may miss entries inserted after this dump started,
2675          * or entries deleted before they are reached.
2676          *
2677          * We need to make sure the mdev won't disappear while
2678          * we are looking at it, and revalidate our iterators
2679          * on each iteration.
2680          */
2681
2682         /* synchronize with conn_create()/conn_destroy() */
2683         rcu_read_lock();
2684         /* revalidate iterator position */
2685         list_for_each_entry_rcu(tmp, &drbd_tconns, all_tconn) {
2686                 if (pos == NULL) {
2687                         /* first iteration */
2688                         pos = tmp;
2689                         tconn = pos;
2690                         break;
2691                 }
2692                 if (tmp == pos) {
2693                         tconn = pos;
2694                         break;
2695                 }
2696         }
2697         if (tconn) {
2698 next_tconn:
2699                 mdev = idr_get_next(&tconn->volumes, &volume);
2700                 if (!mdev) {
2701                         /* No more volumes to dump on this tconn.
2702                          * Advance tconn iterator. */
2703                         pos = list_entry_rcu(tconn->all_tconn.next,
2704                                              struct drbd_tconn, all_tconn);
2705                         /* Did we dump any volume on this tconn yet? */
2706                         if (volume != 0) {
2707                                 /* If we reached the end of the list,
2708                                  * or only a single resource dump was requested,
2709                                  * we are done. */
2710                                 if (&pos->all_tconn == &drbd_tconns || cb->args[2])
2711                                         goto out;
2712                                 volume = 0;
2713                                 tconn = pos;
2714                                 goto next_tconn;
2715                         }
2716                 }
2717
2718                 dh = genlmsg_put(skb, NETLINK_CB(cb->skb).pid,
2719                                 cb->nlh->nlmsg_seq, &drbd_genl_family,
2720                                 NLM_F_MULTI, DRBD_ADM_GET_STATUS);
2721                 if (!dh)
2722                         goto out;
2723
2724                 if (!mdev) {
2725                         /* this is a tconn without a single volume */
2726                         dh->minor = -1U;
2727                         dh->ret_code = NO_ERROR;
2728                         if (nla_put_drbd_cfg_context(skb, tconn, VOLUME_UNSPECIFIED))
2729                                 genlmsg_cancel(skb, dh);
2730                         else
2731                                 genlmsg_end(skb, dh);
2732                         goto out;
2733                 }
2734
2735                 D_ASSERT(mdev->vnr == volume);
2736                 D_ASSERT(mdev->tconn == tconn);
2737
2738                 dh->minor = mdev_to_minor(mdev);
2739                 dh->ret_code = NO_ERROR;
2740
2741                 if (nla_put_status_info(skb, mdev, NULL)) {
2742                         genlmsg_cancel(skb, dh);
2743                         goto out;
2744                 }
2745                 genlmsg_end(skb, dh);
2746         }
2747
2748 out:
2749         rcu_read_unlock();
2750         /* where to start the next iteration */
2751         cb->args[0] = (long)pos;
2752         cb->args[1] = (pos == tconn) ? volume + 1 : 0;
2753
2754         /* No more tconns/volumes/minors found results in an empty skb.
2755          * Which will terminate the dump. */
2756         return skb->len;
2757 }
2758
2759 /*
2760  * Request status of all resources, or of all volumes within a single resource.
2761  *
2762  * This is a dump, as the answer may not fit in a single reply skb otherwise.
2763  * Which means we cannot use the family->attrbuf or other such members, because
2764  * dump is NOT protected by the genl_lock().  During dump, we only have access
2765  * to the incoming skb, and need to opencode "parsing" of the nlattr payload.
2766  *
2767  * Once things are setup properly, we call into get_one_status().
2768  */
2769 int drbd_adm_get_status_all(struct sk_buff *skb, struct netlink_callback *cb)
2770 {
2771         const unsigned hdrlen = GENL_HDRLEN + GENL_MAGIC_FAMILY_HDRSZ;
2772         struct nlattr *nla;
2773         const char *resource_name;
2774         struct drbd_tconn *tconn;
2775         int maxtype;
2776
2777         /* Is this a followup call? */
2778         if (cb->args[0]) {
2779                 /* ... of a single resource dump,
2780                  * and the resource iterator has been advanced already? */
2781                 if (cb->args[2] && cb->args[2] != cb->args[0])
2782                         return 0; /* DONE. */
2783                 goto dump;
2784         }
2785
2786         /* First call (from netlink_dump_start).  We need to figure out
2787          * which resource(s) the user wants us to dump. */
2788         nla = nla_find(nlmsg_attrdata(cb->nlh, hdrlen),
2789                         nlmsg_attrlen(cb->nlh, hdrlen),
2790                         DRBD_NLA_CFG_CONTEXT);
2791
2792         /* No explicit context given.  Dump all. */
2793         if (!nla)
2794                 goto dump;
2795         maxtype = ARRAY_SIZE(drbd_cfg_context_nl_policy) - 1;
2796         nla = drbd_nla_find_nested(maxtype, nla, __nla_type(T_ctx_resource_name));
2797         if (IS_ERR(nla))
2798                 return PTR_ERR(nla);
2799         /* context given, but no name present? */
2800         if (!nla)
2801                 return -EINVAL;
2802         resource_name = nla_data(nla);
2803         tconn = conn_get_by_name(resource_name);
2804
2805         if (!tconn)
2806                 return -ENODEV;
2807
2808         kref_put(&tconn->kref, &conn_destroy); /* get_one_status() (re)validates tconn by itself */
2809
2810         /* prime iterators, and set "filter" mode mark:
2811          * only dump this tconn. */
2812         cb->args[0] = (long)tconn;
2813         /* cb->args[1] = 0; passed in this way. */
2814         cb->args[2] = (long)tconn;
2815
2816 dump:
2817         return get_one_status(skb, cb);
2818 }
2819
2820 int drbd_adm_get_timeout_type(struct sk_buff *skb, struct genl_info *info)
2821 {
2822         enum drbd_ret_code retcode;
2823         struct timeout_parms tp;
2824         int err;
2825
2826         retcode = drbd_adm_prepare(skb, info, DRBD_ADM_NEED_MINOR);
2827         if (!adm_ctx.reply_skb)
2828                 return retcode;
2829         if (retcode != NO_ERROR)
2830                 goto out;
2831
2832         tp.timeout_type =
2833                 adm_ctx.mdev->state.pdsk == D_OUTDATED ? UT_PEER_OUTDATED :
2834                 test_bit(USE_DEGR_WFC_T, &adm_ctx.mdev->flags) ? UT_DEGRADED :
2835                 UT_DEFAULT;
2836
2837         err = timeout_parms_to_priv_skb(adm_ctx.reply_skb, &tp);
2838         if (err) {
2839                 nlmsg_free(adm_ctx.reply_skb);
2840                 return err;
2841         }
2842 out:
2843         drbd_adm_finish(info, retcode);
2844         return 0;
2845 }
2846
2847 int drbd_adm_start_ov(struct sk_buff *skb, struct genl_info *info)
2848 {
2849         struct drbd_conf *mdev;
2850         enum drbd_ret_code retcode;
2851
2852         retcode = drbd_adm_prepare(skb, info, DRBD_ADM_NEED_MINOR);
2853         if (!adm_ctx.reply_skb)
2854                 return retcode;
2855         if (retcode != NO_ERROR)
2856                 goto out;
2857
2858         mdev = adm_ctx.mdev;
2859         if (info->attrs[DRBD_NLA_START_OV_PARMS]) {
2860                 /* resume from last known position, if possible */
2861                 struct start_ov_parms parms =
2862                         { .ov_start_sector = mdev->ov_start_sector };
2863                 int err = start_ov_parms_from_attrs(&parms, info);
2864                 if (err) {
2865                         retcode = ERR_MANDATORY_TAG;
2866                         drbd_msg_put_info(from_attrs_err_to_txt(err));
2867                         goto out;
2868                 }
2869                 /* w_make_ov_request expects position to be aligned */
2870                 mdev->ov_start_sector = parms.ov_start_sector & ~BM_SECT_PER_BIT;
2871         }
2872         /* If there is still bitmap IO pending, e.g. previous resync or verify
2873          * just being finished, wait for it before requesting a new resync. */
2874         wait_event(mdev->misc_wait, !test_bit(BITMAP_IO, &mdev->flags));
2875         retcode = drbd_request_state(mdev,NS(conn,C_VERIFY_S));
2876 out:
2877         drbd_adm_finish(info, retcode);
2878         return 0;
2879 }
2880
2881
2882 int drbd_adm_new_c_uuid(struct sk_buff *skb, struct genl_info *info)
2883 {
2884         struct drbd_conf *mdev;
2885         enum drbd_ret_code retcode;
2886         int skip_initial_sync = 0;
2887         int err;
2888         struct new_c_uuid_parms args;
2889
2890         retcode = drbd_adm_prepare(skb, info, DRBD_ADM_NEED_MINOR);
2891         if (!adm_ctx.reply_skb)
2892                 return retcode;
2893         if (retcode != NO_ERROR)
2894                 goto out_nolock;
2895
2896         mdev = adm_ctx.mdev;
2897         memset(&args, 0, sizeof(args));
2898         if (info->attrs[DRBD_NLA_NEW_C_UUID_PARMS]) {
2899                 err = new_c_uuid_parms_from_attrs(&args, info);
2900                 if (err) {
2901                         retcode = ERR_MANDATORY_TAG;
2902                         drbd_msg_put_info(from_attrs_err_to_txt(err));
2903                         goto out_nolock;
2904                 }
2905         }
2906
2907         mutex_lock(mdev->state_mutex); /* Protects us against serialized state changes. */
2908
2909         if (!get_ldev(mdev)) {
2910                 retcode = ERR_NO_DISK;
2911                 goto out;
2912         }
2913
2914         /* this is "skip initial sync", assume to be clean */
2915         if (mdev->state.conn == C_CONNECTED && mdev->tconn->agreed_pro_version >= 90 &&
2916             mdev->ldev->md.uuid[UI_CURRENT] == UUID_JUST_CREATED && args.clear_bm) {
2917                 dev_info(DEV, "Preparing to skip initial sync\n");
2918                 skip_initial_sync = 1;
2919         } else if (mdev->state.conn != C_STANDALONE) {
2920                 retcode = ERR_CONNECTED;
2921                 goto out_dec;
2922         }
2923
2924         drbd_uuid_set(mdev, UI_BITMAP, 0); /* Rotate UI_BITMAP to History 1, etc... */
2925         drbd_uuid_new_current(mdev); /* New current, previous to UI_BITMAP */
2926
2927         if (args.clear_bm) {
2928                 err = drbd_bitmap_io(mdev, &drbd_bmio_clear_n_write,
2929                         "clear_n_write from new_c_uuid", BM_LOCKED_MASK);
2930                 if (err) {
2931                         dev_err(DEV, "Writing bitmap failed with %d\n",err);
2932                         retcode = ERR_IO_MD_DISK;
2933                 }
2934                 if (skip_initial_sync) {
2935                         drbd_send_uuids_skip_initial_sync(mdev);
2936                         _drbd_uuid_set(mdev, UI_BITMAP, 0);
2937                         drbd_print_uuids(mdev, "cleared bitmap UUID");
2938                         spin_lock_irq(&mdev->tconn->req_lock);
2939                         _drbd_set_state(_NS2(mdev, disk, D_UP_TO_DATE, pdsk, D_UP_TO_DATE),
2940                                         CS_VERBOSE, NULL);
2941                         spin_unlock_irq(&mdev->tconn->req_lock);
2942                 }
2943         }
2944
2945         drbd_md_sync(mdev);
2946 out_dec:
2947         put_ldev(mdev);
2948 out:
2949         mutex_unlock(mdev->state_mutex);
2950 out_nolock:
2951         drbd_adm_finish(info, retcode);
2952         return 0;
2953 }
2954
2955 static enum drbd_ret_code
2956 drbd_check_resource_name(const char *name)
2957 {
2958         if (!name || !name[0]) {
2959                 drbd_msg_put_info("resource name missing");
2960                 return ERR_MANDATORY_TAG;
2961         }
2962         /* if we want to use these in sysfs/configfs/debugfs some day,
2963          * we must not allow slashes */
2964         if (strchr(name, '/')) {
2965                 drbd_msg_put_info("invalid resource name");
2966                 return ERR_INVALID_REQUEST;
2967         }
2968         return NO_ERROR;
2969 }
2970
2971 int drbd_adm_new_resource(struct sk_buff *skb, struct genl_info *info)
2972 {
2973         enum drbd_ret_code retcode;
2974         struct res_opts res_opts;
2975         int err;
2976
2977         retcode = drbd_adm_prepare(skb, info, 0);
2978         if (!adm_ctx.reply_skb)
2979                 return retcode;
2980         if (retcode != NO_ERROR)
2981                 goto out;
2982
2983         set_res_opts_defaults(&res_opts);
2984         err = res_opts_from_attrs(&res_opts, info);
2985         if (err && err != -ENOMSG) {
2986                 retcode = ERR_MANDATORY_TAG;
2987                 drbd_msg_put_info(from_attrs_err_to_txt(err));
2988                 goto out;
2989         }
2990
2991         retcode = drbd_check_resource_name(adm_ctx.resource_name);
2992         if (retcode != NO_ERROR)
2993                 goto out;
2994
2995         if (adm_ctx.tconn) {
2996                 if (info->nlhdr->nlmsg_flags & NLM_F_EXCL) {
2997                         retcode = ERR_INVALID_REQUEST;
2998                         drbd_msg_put_info("resource exists");
2999                 }
3000                 /* else: still NO_ERROR */
3001                 goto out;
3002         }
3003
3004         if (!conn_create(adm_ctx.resource_name, &res_opts))
3005                 retcode = ERR_NOMEM;
3006 out:
3007         drbd_adm_finish(info, retcode);
3008         return 0;
3009 }
3010
3011 int drbd_adm_add_minor(struct sk_buff *skb, struct genl_info *info)
3012 {
3013         struct drbd_genlmsghdr *dh = info->userhdr;
3014         enum drbd_ret_code retcode;
3015
3016         retcode = drbd_adm_prepare(skb, info, DRBD_ADM_NEED_RESOURCE);
3017         if (!adm_ctx.reply_skb)
3018                 return retcode;
3019         if (retcode != NO_ERROR)
3020                 goto out;
3021
3022         /* FIXME drop minor_count parameter, limit to MINORMASK */
3023         if (dh->minor >= minor_count) {
3024                 drbd_msg_put_info("requested minor out of range");
3025                 retcode = ERR_INVALID_REQUEST;
3026                 goto out;
3027         }
3028         if (adm_ctx.volume > DRBD_VOLUME_MAX) {
3029                 drbd_msg_put_info("requested volume id out of range");
3030                 retcode = ERR_INVALID_REQUEST;
3031                 goto out;
3032         }
3033
3034         /* drbd_adm_prepare made sure already
3035          * that mdev->tconn and mdev->vnr match the request. */
3036         if (adm_ctx.mdev) {
3037                 if (info->nlhdr->nlmsg_flags & NLM_F_EXCL)
3038                         retcode = ERR_MINOR_EXISTS;
3039                 /* else: still NO_ERROR */
3040                 goto out;
3041         }
3042
3043         retcode = conn_new_minor(adm_ctx.tconn, dh->minor, adm_ctx.volume);
3044 out:
3045         drbd_adm_finish(info, retcode);
3046         return 0;
3047 }
3048
3049 static enum drbd_ret_code adm_delete_minor(struct drbd_conf *mdev)
3050 {
3051         if (mdev->state.disk == D_DISKLESS &&
3052             /* no need to be mdev->state.conn == C_STANDALONE &&
3053              * we may want to delete a minor from a live replication group.
3054              */
3055             mdev->state.role == R_SECONDARY) {
3056                 idr_remove(&mdev->tconn->volumes, mdev->vnr);
3057                 idr_remove(&minors, mdev_to_minor(mdev));
3058                 del_gendisk(mdev->vdisk);
3059                 synchronize_rcu();
3060                 kref_put(&mdev->kref, &drbd_minor_destroy);
3061                 return NO_ERROR;
3062         } else
3063                 return ERR_MINOR_CONFIGURED;
3064 }
3065
3066 int drbd_adm_delete_minor(struct sk_buff *skb, struct genl_info *info)
3067 {
3068         enum drbd_ret_code retcode;
3069
3070         retcode = drbd_adm_prepare(skb, info, DRBD_ADM_NEED_MINOR);
3071         if (!adm_ctx.reply_skb)
3072                 return retcode;
3073         if (retcode != NO_ERROR)
3074                 goto out;
3075
3076         retcode = adm_delete_minor(adm_ctx.mdev);
3077 out:
3078         drbd_adm_finish(info, retcode);
3079         return 0;
3080 }
3081
3082 int drbd_adm_down(struct sk_buff *skb, struct genl_info *info)
3083 {
3084         int retcode; /* enum drbd_ret_code rsp. enum drbd_state_rv */
3085         struct drbd_conf *mdev;
3086         unsigned i;
3087
3088         retcode = drbd_adm_prepare(skb, info, 0);
3089         if (!adm_ctx.reply_skb)
3090                 return retcode;
3091         if (retcode != NO_ERROR)
3092                 goto out;
3093
3094         if (!adm_ctx.tconn) {
3095                 retcode = ERR_RES_NOT_KNOWN;
3096                 goto out;
3097         }
3098
3099         /* demote */
3100         idr_for_each_entry(&adm_ctx.tconn->volumes, mdev, i) {
3101                 retcode = drbd_set_role(mdev, R_SECONDARY, 0);
3102                 if (retcode < SS_SUCCESS) {
3103                         drbd_msg_put_info("failed to demote");
3104                         goto out;
3105                 }
3106         }
3107
3108         retcode = conn_try_disconnect(adm_ctx.tconn, 0);
3109         if (retcode < SS_SUCCESS) {
3110                 drbd_msg_put_info("failed to disconnect");
3111                 goto out;
3112         }
3113
3114         /* detach */
3115         idr_for_each_entry(&adm_ctx.tconn->volumes, mdev, i) {
3116                 retcode = adm_detach(mdev);
3117                 if (retcode < SS_SUCCESS) {
3118                         drbd_msg_put_info("failed to detach");
3119                         goto out;
3120                 }
3121         }
3122
3123         /* If we reach this, all volumes (of this tconn) are Secondary,
3124          * Disconnected, Diskless, aka Unconfigured. Make sure all threads have
3125          * actually stopped, state handling only does drbd_thread_stop_nowait(). */
3126         drbd_thread_stop(&adm_ctx.tconn->worker);
3127
3128         /* Now, nothing can fail anymore */
3129
3130         /* delete volumes */
3131         idr_for_each_entry(&adm_ctx.tconn->volumes, mdev, i) {
3132                 retcode = adm_delete_minor(mdev);
3133                 if (retcode != NO_ERROR) {
3134                         /* "can not happen" */
3135                         drbd_msg_put_info("failed to delete volume");
3136                         goto out;
3137                 }
3138         }
3139
3140         /* delete connection */
3141         if (conn_lowest_minor(adm_ctx.tconn) < 0) {
3142                 list_del_rcu(&adm_ctx.tconn->all_tconn);
3143                 synchronize_rcu();
3144                 kref_put(&adm_ctx.tconn->kref, &conn_destroy);
3145
3146                 retcode = NO_ERROR;
3147         } else {
3148                 /* "can not happen" */
3149                 retcode = ERR_RES_IN_USE;
3150                 drbd_msg_put_info("failed to delete connection");
3151         }
3152         goto out;
3153 out:
3154         drbd_adm_finish(info, retcode);
3155         return 0;
3156 }
3157
3158 int drbd_adm_del_resource(struct sk_buff *skb, struct genl_info *info)
3159 {
3160         enum drbd_ret_code retcode;
3161
3162         retcode = drbd_adm_prepare(skb, info, DRBD_ADM_NEED_RESOURCE);
3163         if (!adm_ctx.reply_skb)
3164                 return retcode;
3165         if (retcode != NO_ERROR)
3166                 goto out;
3167
3168         if (conn_lowest_minor(adm_ctx.tconn) < 0) {
3169                 list_del_rcu(&adm_ctx.tconn->all_tconn);
3170                 synchronize_rcu();
3171                 kref_put(&adm_ctx.tconn->kref, &conn_destroy);
3172
3173                 retcode = NO_ERROR;
3174         } else {
3175                 retcode = ERR_RES_IN_USE;
3176         }
3177
3178         if (retcode == NO_ERROR)
3179                 drbd_thread_stop(&adm_ctx.tconn->worker);
3180 out:
3181         drbd_adm_finish(info, retcode);
3182         return 0;
3183 }
3184
3185 void drbd_bcast_event(struct drbd_conf *mdev, const struct sib_info *sib)
3186 {
3187         static atomic_t drbd_genl_seq = ATOMIC_INIT(2); /* two. */
3188         struct sk_buff *msg;
3189         struct drbd_genlmsghdr *d_out;
3190         unsigned seq;
3191         int err = -ENOMEM;
3192
3193         seq = atomic_inc_return(&drbd_genl_seq);
3194         msg = genlmsg_new(NLMSG_GOODSIZE, GFP_NOIO);
3195         if (!msg)
3196                 goto failed;
3197
3198         err = -EMSGSIZE;
3199         d_out = genlmsg_put(msg, 0, seq, &drbd_genl_family, 0, DRBD_EVENT);
3200         if (!d_out) /* cannot happen, but anyways. */
3201                 goto nla_put_failure;
3202         d_out->minor = mdev_to_minor(mdev);
3203         d_out->ret_code = NO_ERROR;
3204
3205         if (nla_put_status_info(msg, mdev, sib))
3206                 goto nla_put_failure;
3207         genlmsg_end(msg, d_out);
3208         err = drbd_genl_multicast_events(msg, 0);
3209         /* msg has been consumed or freed in netlink_broadcast() */
3210         if (err && err != -ESRCH)
3211                 goto failed;
3212
3213         return;
3214
3215 nla_put_failure:
3216         nlmsg_free(msg);
3217 failed:
3218         dev_err(DEV, "Error %d while broadcasting event. "
3219                         "Event seq:%u sib_reason:%u\n",
3220                         err, seq, sib->sib_reason);
3221 }